SyntaxError: 'break' outside loop in Python

avatar

Borislav Hadzhiev

Last updated: Apr 25, 2022

banner

Photo from Unsplash

SyntaxError: 'break' outside loop in Python #

The Python "SyntaxError: 'break' outside loop" occurs when we use the break statement outside of a loop. To solve the error, use a return statement to return a value from a function, or use the sys.exit() method to exit the interpreter.

syntaxerror break outside loop

Here is an example of how the error occurs.

main.py
if len('hi') == 2: # ⛔️ SyntaxError: 'break' outside loop break

The break statement can only be used inside of for or while loops.

If you meant to return a value from a function, use a return statement instead.

main.py
def example(): if len('hi') == 2: return 100 return 0 result = example() print(result) # 👉️ 100

The return statement can be used to return a value and exit the function.

If you don't need to return a specific value and just need to exit the function, simply return.

If you need to signal an intention to exit the interpreter, use the sys.exit() method.

main.py
import sys print('before') # ✅ this runs sys.exit() print('after') # ⛔️ this never runs

The sys.exit method can be used to signal an intention to exit the interpreter.

The last line from the code sample is never ran.

The break statement breaks out of the innermost enclosing for or while loop.

main.py
for i in range(5): if i == 3: break print(i) # 👉️ 0 1 2

The if statement checks if the i variable stores a value of 3, and if it does, we break out of the for loop.

Here is an example of using the break statement in a while loop.

main.py
i = 0 while i < 5: print(i) # 👉️ 0 1 2 i += 1 if i == 3: break

The while loop iterates until its condition returns false or the break statement is used.

Conclusion #

The Python "SyntaxError: 'break' outside loop" occurs when we use the break statement outside of a loop. To solve the error, use a return statement to return a value from a function, or use the sys.exit() method to exit the interpreter.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.