Python - Decision control and looping statement - Continue Statement Tutorial
Continue statement is used to stop the current iteration and continue with the next iteration. It is used to skip the current iteration.
Continue statement can be performed in any loop( for , while)
Syntax-
continue;
Example-
# List of number
number = [4, 1, 2, 27, 25, 73]
# iterate over the list of number
for val in number:
if(val==27):
continue;
print(val)
Output-
4
1
2
25
73
In above program, if val is 27 it will skip the current iteration and will print the next number i.e [25, 73] .
While in break statement, it the val = 27 then it will get stop and will not print next number i.e [25, 73] .
So, for break statement output will be –
4
1
2
Continue statement in while loop
Example-
i=1
while i <= 6:
i=i+1
if(i==3):
continue
print(i)
Output-
2
4
5
6
7
Nested Loop
Without Continue 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 Continue 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):
continue;
print("a="+str(a)+" b="+str(b))
Output-
a=1 b=2
a=1 b=4
a=2 b=2
a=2 b=4
a=3 b=2
a=3 b=4
In the above program, whenever in the inner loop b become 3, continue statement will skip the current iteration, and continue with the next iteration.
.