Python Break and Continue statement
Python break statement
It is sometimes desirable to skip some statements inside the loop or terminate the loop immediately without checking the test expression. In such cases we can use break statements in Python. The break statement allows you to exit a loop from any point within its body, bypassing its normal termination expression.
As seen in the above image, when the break statement is encountered inside a loop, the loop is immediately terminated, and program control resumes at the next statement following the loop.
break statement in while loop
n=1
while True:
print (n)
n+=1
if n==5:
break
print("After Break")
output
1
2
3
4
After Break
In the above program, when n==5, the break statement executed and immediately terminated the while loop and the program control resumes at the next statement.
break statement in while loop
for str in "Python":
if str == "t":
break
print(str)
print("Exit from loop")
output
P
y
Exit from loop
Python continue statement
Continue statement works like break but instead of forcing termination, it forces the next iteration of the loop to take place and skipping the rest of the code.continue statement in while loop
n=0
while n < 5:
n+=1
if n==3:
continue
print (n)
print("Loop Over")
output
1
2
4
5
Loop Over
In the above program, we can see in the output the 3 is missing. It is because when n==3 the loop encounter the continue statement and control go back to start of the loop.
continue statement in for loop
n=0
for n in range(5):
n+=1
if n==3:
continue
print(n)
print("Loop Over")
output
1
2
4
5
Loop Over
In the above program, we can see in the output the 3 is missing. It is because when n==3 the loop encounter the continue statement and control go back to start of the loop.
Related Topics