In this Python tutorial, we will learn about break statement, and how to use this break statement to abruptly complete the execution of a For loop, While loop, etc., with examples.
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 break statement
Following is the syntax of Python break statement.
break
Examples
1. For loop with break statement
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.
Python Program
for number in [1, 2, 3, 5, 6, 10, 11, 12]:
if number==6:
break
print(number)
print('Bye')
Output
1
2
3
5
Bye
If there is no break statement, all the elements of the list would have printed to the console.
2. While loop with break statement
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.
Python Program
i=1
while i < 11:
if i==6:
break
print(i)
i=i+1
print('Bye')
Output
1
2
3
4
5
Bye
3. break statement outside loop
In the following example, we will try to use break statement outside for or while loop statement.
Python Program
i=1
if i==2:
break
print('Bye')
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.