Python Continue Statement
In Python, loops automate and repeat processes in a cost-effective manner. However, there may be occasions when you wish to entirely exit the loop, skip an iteration, or ignore the condition. Loop control statements can be used to do this. Continue is a loop control statement that allows you to change the loop's flow.
The continue statement is a loop control statement that forces the loop to execute the next iteration while skipping the rest of the code inside the loop for the current iteration only. When the continue statement is executed in the loop, the code inside the loop following the continue statement is skipped for the current iteration only, and the loop's next iteration begins.
Let us look at some examples to understand the concept better.
Consider the following scenario: you need to develop a programme that prints numbers from 1 to 10, but not 6. It is mentioned that you must perform this with a loop, and that you may only use one loop. Here's when the continue statement comes into play. What we can do here is run a loop from 1 to 10 and compare the value of the iterator with 6 every time. If it equals 6, we'll use the continue statement to skip to the next iteration without writing anything; otherwise, the value will be printed.
# Python program to
# demonstrate continue
# statement
# loop from 1 to 10
for i in range(1, 11):
# If i is equals to 6,
# continue to next iteration
# without printing
if i == 6:
continue
else:
# otherwise print the value
# of i
print(i, end=" ")
Output:
1 2 3 4 5 7 8 9 10
The continue statement, also borrowed from C just like the break statement, continues with the next iteration of the loop:
>>> for num in range(2, 10):
... if num % 2 == 0:
... print("Found an even number", num)
... continue
... print("Found an odd number", num)
Output:
Found an even number 2
Found an odd number 3
Found an even number 4
Found an odd number 5
Found an even number 6
Found an odd number 7
Found an even number 8
Found an odd number 9
Let’s see how the python continue statement works with different loops in the program.
Continue with for loop
t_ints = (1, 2, 3, 4, 5)
for i in t_ints:
if i == 3:
continue
print(f'Processing integer {i}')
print("Done")
Output:
Processing integer 1
Processing integer 2
Processing integer 4
Processing integer 5
Done
Continue with a while loop
count = 10
while count > 0:
if count % 3 == 0:
count -= 1
continue
print(f'Processing Number {count}')
count -= 1
Output:
Processing Number 10
Processing Number 8
Processing Number 7
Processing Number 5
Processing Number 4
Processing Number 2
Processing Number 1
Continue with a nested loop
list_of_tuples = [(1, 2), (3, 4), (5, 6, 7)]
for t in list_of_tuples:
# don't process tuple with more than 2 elements
if len(t) > 2:
continue
for i in t:
# don't process if the tuple element value is 3
if i == 3:
continue
print(f'Processing {i}')
Output:
Processing 1
Processing 2
Processing 4