Stopping a loop is great, but what if we would like to just skip this one time? What if we don’t want to execute the rest of the loop for this specific value, but want to keep the loop going?
To do that we can use the continue statement, which would continue the execution to the next round of the loop:
numbers = [1, 5, 6, 4, 0, -4, 8, 11, 2]
even_sum = 0
for n in numbers:
if n % 2 != 0:
continue
even_sum += n
print(n)
print('Sum:', even_sum)
6
4
0
-4
8
2
Sum: 16
This program will skip the execution for each n that n % 2 != 0 (n is not even).
continue skips the execution of whatever comes after it. So, everything before continue is still getting executed. Python has to reach the statement continue to know that it needs to skip the rest.
Challenge
Given 10 integers, the program should print each number if all the conditions hold:
It’s odd
It lies outside the range [3, 7]
It lies outside the range [11, 13]
It lies outside the range [17, 23]
Input
Output
12
9
6
0
1
-1
41
28
27
17
9
1
-1
41
27
Note that [l, r] indicates the range from l to r where both l and r are inclusive.
Tip
You can skip the execution of the loop for each of the cases where the condition does not hold (so, you can have 4 if statements with continue and a print statement at the end).