Use a break statement to terminate a loop suddenly by triggering a condition. It stops a loop from executing for any further iterations. The break statement can be used in any type of loop – while loop and for-loop.
The break keyword is only be used inside a loop. But if we try to break outside of a loop, then you will get the “SyntaxError: ‘break’ outside loop” error.
n = 10
if n < 11:
print('The number is less than 11')
else:
break
Output:
Solution Break Outside loop Python
Simple example code. Use exceptions to stop a program and with an error message.
Note: The break outside Loop error means that your code has a break statement that is not inside a loop.
n = 10
if n < 9:
print('The number is less than 9')
else:
raise Exception("The number is not less than 9")
Output: Exception: The number is not less than 9
Using break outside a loop solves nothing.
A break statement is meant to be inside the loop(either for or a while) because its main function is to break out of the loop before the loop finishes.
Difference between break, exit, and return:
BREAK | EXIT | RETURN |
Keyword | System Call | Instruction |
exit from a loop | exit from a program and return the control back to OS | return a value from a function |
Do comment if you have any doubts or suggestions about this Python Break keyword tutorial.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.