Python course menu
Python continue Statement: Skip to the Next Loop Iteration
Learn the Python continue statement: skip the rest of the current loop iteration, filter out unwanted items, skip blank and comment lines, use continue in while loops safely, and compare continue with break.
On this page
continue skips the rest of the current iteration and jumps straight to the next one. The loop keeps running; only this one pass is cut short. It is a tidy way to ignore items you do not want to process.
continue in a for loop#
Print only the odd numbers:
for n in range(1, 8):
if n % 2 == 0:
continue
print(n)1
3
5
7For even numbers, continue jumps back to the top of the loop, so print(n) is skipped.
Skipping unwanted data#
continue shines when cleaning data. Skip empty lines and comments in a simple settings file:
lines = ["# comment", "name=Asha", "", "city=Pune", "# another"]
for line in lines:
if not line or line.startswith("#"):
continue
key, value = line.split("=")
print(key, "->", value)name -> Asha
city -> PunePutting the "skip" checks at the top keeps the main work at a single indentation level, the loop version of the guard clauses in Nested Conditions.
Another example: ignore invalid exam scores but keep the valid ones:
scores = [72, -1, 88, 105, 64]
valid = []
for s in scores:
if s < 0 or s > 100:
print("skipping invalid score", s)
continue
valid.append(s)
print(valid)skipping invalid score -1
skipping invalid score 105
[72, 88, 64]continue in a while loop#
In a while loop, make sure the loop variable is updated before continue, or the loop may never end:
n = 0
while n < 6:
n += 1 # update first
if n == 3:
continue
print(n)1
2
4
5
6If n += 1 came after the continue, then once n reached 3 it would never change again, and the loop would run forever.
continue vs break#
Common mistakes#
Practice#
Practice exercise
Add up all numbers from 1 to 20, skipping multiples of 3. Print the total.
Show hint
if n % 3 == 0: continue, then total += n.
Show solution
total = 0
for n in range(1, 21):
if n % 3 == 0:
continue
total += n
print(total)147The sum of 1 to 20 is 210; the skipped multiples of 3 (3, 6, 9, 12, 15, 18) add up to 63, and 210 − 63 = 147.
Key takeaway#
Finished this lesson?