Sub topic 6
Skipping an iteration with continue
What you should already know
This chapter assumes you can write a basic while loop and know how its condition is checked. It also assumes you can use if statements with correct indentation, and that you have seen break end a loop early. You should be comfortable with +=, comparison operators, and truthiness (for example, an empty string counts as false). The main risk with continue is a loop that never ends, so the chapter spends most of its time on that.
What continue does
The continue statement ends the current pass through the loop body. Python skips the rest of the body and goes straight back to the loop condition. If the condition is still true, the next pass starts. If it is false, the loop ends normally.
continue does not leave the loop, and it does not re-run the body. It jumps to the condition check.
i = 0
while i < 10:
i += 1
if i % 2 == 0:
continue
print(i)This prints 1, 3, 5, 7 and 9. Each pass first increments i. When i is even, continue skips the print call and Python checks i < 10 again. When i is odd, execution reaches print.
In a while loop, continue goes back to the condition and nowhere else. Nothing happens automatically on the way. This differs from a for loop, where continue moves on to the next item from the iterator. That difference is the source of the most common continue bug.
The update-before-continue rule
A while loop ends only when something in the body changes the state the condition reads. If continue skips the statement that makes that change, the loop can stop making progress.
i = 0
while i < 10:
if i % 2 == 0:
continue # bug: i is never incremented, so this loops forever
i += 1Here i starts at 0, which is even. continue jumps back to the condition, i is still 0, and the same thing happens again. The i += 1 line is never reached. The program hangs and uses a full CPU core until you interrupt it with Ctrl+C.
There are three common ways to fix this.
- Update the state before the
continuetest, as in the first example. This is usually the clearest option. - Repeat the update inside the branch that calls
continue. - Avoid
continueand put the work inside anif.
The second fix looks like this:
i = 0
while i < 10:
if i % 2 == 0:
i += 1
continue
print(i)
i += 1This prints 1, 3, 5, 7 and 9, but the update appears twice. If you later change one copy and forget the other, you get a bug. Prefer moving the single update to the top of the body, or using a for loop if the loop is just counting.
When skipping an update is correct
The rule above does not mean every continue must be preceded by an update to the loop variable. What matters is that each pass makes progress toward ending the loop. Sometimes the progress comes from consuming input, and the counter should change only for valid items.
replies = iter(["", "abc", "42", "7"])
total = 0
count = 0
while count < 2:
reply = next(replies)
if not reply.isdigit():
print(f"skipping {reply!r}")
continue
total += int(reply)
count += 1
print(total)The output is:
skipping ''
skipping 'abc'
49The loop wants two valid numbers, so count must only change when a reply is valid. The continue deliberately skips count += 1. The loop still ends because next(replies) takes a new value on every pass, so each pass uses up input. If replies ran out, next would raise StopIteration, which is an error you would handle instead of an infinite loop. With real keyboard input you would call input() in the same place.
The question to ask is "does every pass consume something or change something that brings the end closer?" It is not "did I increment a counter?"
Using continue as a guard
The best use of continue is as a guard clause. You test for a case that needs no processing, skip it, and leave the main logic at the top level of the loop body. This avoids deeply nested if blocks.
Here is a loop that parses configuration lines. It ignores blank lines and comments:
lines = ["# config", "name=demo", "", " ", "port=8080", "# end", "debug=true"]
settings = {}
index = 0
while index < len(lines):
line = lines[index].strip()
index += 1
if not line or line.startswith("#"):
continue
key, value = line.split("=", 1)
settings[key] = value
print(settings)The output is:
{'name': 'demo', 'port': '8080', 'debug': 'true'}The update index += 1 comes right after reading the line and before any continue, so every path advances. The condition not line is true for the empty string, which is falsy. The call split("=", 1) splits on the first equals sign only, so a value that contains = stays intact.
Without continue, you would write the same logic like this:
lines = ["# config", "name=demo", "", " ", "port=8080", "# end", "debug=true"]
settings = {}
index = 0
while index < len(lines):
line = lines[index].strip()
index += 1
if line and not line.startswith("#"):
key, value = line.split("=", 1)
settings[key] = value
print(settings)Both versions work. The guard version scales better. With three or four skip conditions, the nested version grows deeper while the guard version stays flat, with one short if ...: continue per rule.
continue compared with break and if/else
| Tool | Effect | Next step |
|---|---|---|
| `continue` | Ends this pass | Goes to the condition check |
| `break` | Ends the whole loop | Runs the first statement after the loop, and skips the loop `else` |
| `if` / `else` around the work | Chooses which statements run | Falls through to the end of the body, then the condition check |
Use continue when "this item needs no work" is a short, early decision. Use if/else when both branches have real work. Use break when nothing after this point matters.
continue in nested loops
Like break, continue affects only the innermost loop that contains it. The outer loop keeps its own state and carries on as normal.
row = 0
while row < 3:
row += 1
col = 0
while col < 3:
col += 1
if col == 2:
continue
print(row, col)The output is:
1 1
1 3
2 1
2 3
3 1
3 3The continue skips column 2 in the inner loop for each row. It does not skip any rows. If you want to skip the rest of a row and move to the next row, you need another approach. One option is to break out of the inner loop and let the outer body reach its end. Another is to move the inner loop into a function and return.
Notice that col += 1 comes before continue here as well. If you move it to the end of the inner body, the inner loop sticks at col == 2.
continue with try and finally
A continue inside a try block still runs the finally block before the jump happens. Cleanup code is therefore safe.
i = 0
while i < 3:
i += 1
try:
if i == 2:
continue
print("work", i)
finally:
print("cleanup", i)The output is:
work 1
cleanup 1
cleanup 2
work 3
cleanup 3Pass 2 prints cleanup 2 but not work 2. Since Python 3.8 you can also write continue inside a finally block. Avoid it, because it can silently cancel an exception that was propagating.
continue and the loop else clause
A while loop's else block runs when the condition becomes false, unless a break ended the loop. A continue never prevents the else block from running, because it does not leave the loop.
n = 0
while n < 3:
n += 1
if n == 2:
continue
print(n)
else:
print("finished without break")The output is 1, 3, and then finished without break. Only break (or return, or an exception) skips the else.
Common mistakes
- Skipping the update. This is the infinite loop from earlier. The loop condition cannot change because
continuejumps over the line that changes it. Look at the code betweencontinueand the end of the body. If the update is there, move it earlier. - Putting the update after the
continuetest "to keep it tidy". The update is part of the loop's mechanism, not part of the work. Place it where no path can bypass it. - Using
continueas the last statement of the body. It does nothing, since the loop would go back to the condition anyway. Remove it. - Expecting
continueto skip the condition. The condition is always checked aftercontinue. If the condition has side effects, such as the:=operator, those effects happen again. - Expecting an outer loop to be affected.
continuein an inner loop never skips an outer iteration. - Hiding too many
continuestatements. If a body has five of them, a reader must track five exits. Consider splitting the body into a function that returns early, or filtering the data first.
Choosing a different tool
When the loop is just "go through every item and skip some", a for loop is usually better. A for loop advances its iterator automatically, so continue cannot cause the missing-update bug.
for i in range(1, 11):
if i % 2 == 0:
continue
print(i)This prints the same odd numbers with no manual counter. Use while with continue when the amount of progress per pass is not fixed, for example when you consume variable amounts of input or when state changes depend on the data.
Exercises
Exercise
The following loop never stops. Explain why, and rewrite it so it prints 1, 2, 4, 5 (skipping 3) and ends. n = 0 while n < 5: if n == 3: continue n += 1 print(n)
Show answer
When n becomes 3, the test n == 3 is true and continue jumps back to the condition. The line n += 1 is skipped, so n stays 3 and the loop repeats forever. In fact the loop prints 1, 2, 3 before it hangs, because print(n) runs after the increment. A fix is to update first and test the new value: n = 0 while n < 5: n += 1 if n == 3: continue print(n) This prints 1, 2, 4, 5. The increment happens on every pass, so the loop always makes progress.
Exercise
What does this code print, and why does the loop else block run? n = 0 while n < 4: n += 1 if n % 2 == 1: continue print(n) else: print("done")
Show answer
It prints 2, 4 and then done. Odd values of n trigger continue, which skips print. Even values are printed. The loop ends when n reaches 4 and the condition n < 4 becomes false. No break happened, so the else block runs.
Exercise
In the nested loop below, how many lines are printed, and which values of col appear? row = 0 while row < 2: row += 1 col = 0 while col < 4: col += 1 if col % 2 == 0: continue print(row, col)
Show answer
Four lines are printed. In each of the two rows, the inner continue skips the even columns 2 and 4, so only col values 1 and 3 appear. The output is 1 1, 1 3, 2 1, 2 3. The continue affects only the inner loop, so both rows still run.