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: