Break Outside loop Python | Example code

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:

Break Outside loop Python

Soution 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.

Break statement is meant to be inside the loop(either for or while) because its main function is to break out of the loop before the loop finishes.

Difference between break, exit, and return:

BREAKEXITRETURN
KeywordSystem CallInstruction
exit from a loopexit from a program and return the control back to OSreturn a value from a function

Do comment if you have any doubts and suggestions about this Python Break keyword tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.