What is Continue statement in Python ?
Continue
is also a loop control statement just like the break statement. continue
statement is opposite to that of break statement, instead of terminating the loop, it forces to execute the next iteration of the loop.
As the name suggests the continue statement forces the loop to continue or execute the next iteration. When the continue statement is executed in the loop, the code inside the loop following the continue statement will be skipped and the next iteration of the loop will begin.
for i in range(1, 10):
if i == 5:
continue
print(i)
1
2
3
4
6
7
8
9
In the example we have a range from 1 to 10. if “i” is equal to 5 continue statement will be skipped that step and the next iteration of the loop will begin.
Example:
We can use the continue statement in both while and for loops.
Continue with for loop:
for letter in 'Welcome':
if letter == 't':
continue
print(letter)
W
e
c
o
m
e
Continue with while loop:
number = 5
while number > 0:
number = number - 1
if number == 3:
continue
print (number)
4
2
1
0
break VS continue
Using loops in Python automates and repeats the tasks in an efficient manner. But sometimes, there may arise a condition where you want to exit the loop completely, skip an iteration or ignore that condition. These can be done by loop control statements. Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
Break statement in Python is used when you want to stop/terminate the flow of the program using some condition.
Continue
statement is opposite to that of break statement, instead of terminating the loop, it forces to execute the next iteration of the loop.
for i in range(10):
if i % 2:
continue
if i > 7:
break
print(i)
0
2
4
6
- continue