Because break cannot be used to break out of an if statement -it can only break out of loops. That's the way Python (and most other languages) are specified to behave.
What are you trying to do? Perhaps you should use sys.exit() or return instead?
lol = 0
if lol != 10000000000:
break
theoretically, this code should break, but the error says break outside loop. help
Because break cannot be used to break out of an if statement -it can only break out of loops. That's the way Python (and most other languages) are specified to behave.
What are you trying to do? Perhaps you should use sys.exit() or return instead?
Some other common ways this error may show up:
1. Incorrect indentation
Indentation is extremely important in Python. It helps determine the grouping of statements, so if you don't group statements correctly, your code will not work as expected.
Suppose you perform some computation inside a loop and depending on its result, either continue on in the loop or break out of the loop. If you inadvertently put the if-else block outside the loop because you missed the indentation, you will get the error in the title. To solve the error in that case, use indentation correctly.
For example the following will raise the error in the title.
for i in range(10):
print(i) # <--- do something
if i % 3: # <--- break out of loop on some condition
break
The following solves this error:
for i in range(10):
print(i)
if i % 3: # <--- use indentation correctly
break # <--- to break out of loop
Of course your program will probably have much more code than this but the general structure might be the same in which case, see if the proposed solution applies.
I think this issue is exacerbated by some IDEs that use 2 spaces (not the 4 recommended by PEP8) per indentation level by default, which sometimes makes it difficult to see where indentation ends.
2. Include a break statement inside a function
The break statement must be explicitly inside the loop definition; it cannot be nested in a function that will be executed inside a loop.
For example, the following raises the error in the title:
def func(x):
x *= 10
if x > 20: # <--- break out of loop on condition
break
for i in range(10):
func(i) # <--- call function
To solve it, move the conditional check out of the function and put it in the loop.
def func(x):
x *= 10
return x # <--- return the value
for i in range(10):
x = func(i) # <--- call function
if x > 20: # <--- check condition
break