Python Break and Continue statements are control statements executed inside a loop. The continue statement skips according to the conditions inside the loop and the break keyword terminates the loop execution at some point.
Break and Continue in Python
Simple example code of break and continue statements in Python.
A break statement is used inside both the while
and for
loops. It terminates the loop immediately and transfers execution to the new statement after the loop. Exit loop when the variable count becomes equal to 3.
count = 0
while count <= 10:
print(count)
count += 1
if count == 3:
print("Break")
break
Output:
The continue statement causes the loop to skip its current execution at some point and move on to the next iteration.
for i in range(0, 5):
if i == 3:
print("continue")
continue
print(i)
Output:
0
1
2
continue
4
In summary, break
is used to exit the loop completely, while continue
is used to skip the current iteration and proceed to the next iteration of the loop. Both statements are powerful tools for controlling the flow of loops in Python.
Do comment if you have any doubts or suggestions on this Python statement topic.
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.