Ask coding questions

← Back to all posts
mellaluna (1)

If I inserted an If statement into an Elif statement and I'm trying to break the If statement, why does it say that the 'brea' is outside the loop?

firefish (517)

Because the break statements is for use in loops only; not in if statements. However, you might be able to use return for exiting functions, but ifs aren't functions. You could however put it all in a function and use return.

firefish (517)

@mellaluna You could put the if clause inside the while loop, then it would work fine without removing the if statement. Also, the declaration of the variable choice is only inside the while loop. In order to bypass this, you would need to declare the variable with global. Or you could just put the entire if statement inside the while loop, without changing anything else.

a5rocks (793)

@johnstev111 No, python doesn't scope like that:

for i in range(5):
  v = i

print(v)  # outputs `4`
a5rocks (793)

It says that break is not in a loop because it isn't. It's in an if statement, which is not in a loop either.

while True:
  user_says = input('> ')
  if user_says == 'break':

^ that works though, so maybe you can see what you did wrong