Python break
Python break statement is used to come out of a loop without proceeding with the further iterations of the loop.
Python break has to be used only inside a loop. If you use outside a loop, SyntaxError happens.
Once the program control is out of the loop, execution continues with the statements after that loop.
Syntax of Python break
Following is the syntax of Python break statement.
break
Example 1 – Python break in for loop
In the following example, we will use break statement inside Python For loop to come out of the loop and continue with the rest of the statements.
example.py – Python Program
for number in [1, 2, 3, 5, 6, 10, 11, 12]: if number==6: break print(number) print('Bye')Try Online
Output
1 2 3 5 Bye
If there is no break statement, all the elements of the list would have printed to the console.
Example 2 – Python break statement with while loop
In the following example, we will use break statement inside Python While Loop to come out of the loop and continue with the rest of the statements.
example.py – Python Program
i=1 while i < 11: if i==6: break print(i) i=i+1 print('Bye')Try Online
Output
1 2 3 4 5 Bye
Example 3 – Python break statement outside loop statement
In the following example, we will try to use break statement outside for or while loop statement.
example.py – Python Program
i=1 if i==2: break print('Bye')Try Online
Output
File "example1.py", line 4 break ^ SyntaxError: 'break' outside loop
You will get SyntaxError
with the message 'break' outside loop
if you try to use break statement outside for or while loop.
Conclusion
In this Python Tutorial, we learned how to use Python break statement with for and while loops.