Python - Decision control and looping statement - Break Statement Tutorial
The break statement is used to stop the loop even if the condition is true. It is used to come out of the loop, whenever we need it for a given condition.
In the case of a nested loop, it will stop/break the inner loop first, after that it will also stop/break the outer loop.
Break statement can be performed in any loop ( for , while).
Syntax-
break;
Break statement in for loop
Example-
# List of number
number = [4, 1, 2, 27, 25, 73]
# iterate over the list of number
for val in number:
if(val==27):
break;
print(val)
Output-
4
1
2
In above program, if val is 27 it will stop/break whole loop and will not print the next number i.e [25, 73] .
While in continue statement, it will skip val = 27 (current iteration) and print the next number i.e [25, 73] .
So, for continue statement output will be –
4
1
2
25
73
Break statement in while loop
Example-
i=1
while i <= 6:
print(i)
if(i==3):
break;
i=i+1
Output-
1
2
3
Nested Loop
Without break statement-
# a for loop will executed 3 time i.e from 1 to 3
# b for loop will executed 3 time i.e from 2 to 4
for a in range(1,4):
for b in range(2,5):
print("a="+str(a)+" b="+str(b))
Output-
a=1 b=2
a=1 b=3
a=1 b=4
a=2 b=2
a=2 b=3
a=2 b=4
a=3 b=2
a=3 b=3
a=3 b=4
With break statement-
# a for loop will executed 3 time i.e from 1 to 3
# b for loop will executed 3 time i.e from 2 to 4
for a in range(1,4):
for b in range(2,5):
if(b==3):
break;
print("a="+str(a)+" b="+str(b))
Output-
a=1 b=2
a=2 b=2
a=3 b=2
In the above program, whenever in the inner loop b become 3, break statement will stop the inner loop, and come out of the inner loop, after that it will also stop the outer loop.