Python Continue: Syntax, Examples, and Common Mistakes
Python continue skips the rest of the current loop iteration and starts the next one. See syntax, examples, traces, and common mistakes.
You can use continue inside both for and while loops, usually after an if condition identifies a value that should be ignored.
The Python
continuestatement skips the remaining statements in the current iteration and begins the next iteration of the nearest enclosingfororwhileloop.
What Does Continue Do in Python?
continue is a loop-control statement. It changes where execution goes next inside a loop.
The basic pattern is:
for item in items:
if should_skip(item):
continue
process(item)
The if statement decides whether Python reaches continue. The continue statement controls the loop. It does not belong to the if statement, restart a function, or end the loop.
Here is a minimal runnable example:
for number in range(1, 4):
print("start", number)
if number == 2:
continue
print("finish", number)
start 1
finish 1
start 2
start 3
finish 3
Trace the control flow one executed line at a time:
| Step | Current value | Action | Next destination |
|---|---|---|---|
| 1 | none | The for header requests a value and assigns 1 to number | Run the first print |
| 2 | 1 | Print start 1 | Evaluate number == 2 |
| 3 | 1 | The condition is false | Run the final print |
| 4 | 1 | Print finish 1 | Return to the for header |
| 5 | 1 | The for header requests a value and assigns 2 to number | Run the first print |
| 6 | 2 | Print start 2 | Evaluate number == 2 |
| 7 | 2 | The condition is true | Run continue |
| 8 | 2 | Run continue | Return to the for header |
| 9 | 2 | The for header requests a value and assigns 3 to number | Run the first print |
| 10 | 3 | Print start 3 | Evaluate number == 2 |
| 11 | 3 | The condition is false | Run the final print |
| 12 | 3 | Print finish 3 | Return to the for header |
| 13 | 3 | The for header requests another value, but the iterator is exhausted | Leave the loop |
A useful mental model is a conveyor belt. Each iteration puts one item at a workstation. continue sends the current item onward without running the remaining stations, then brings in the next item. It does not switch off the conveyor belt.
continue skips only code that has not run yet in the current iteration. Statements above it have already taken effect, while statements below it are bypassed.
This distinction matters when a loop updates counters, modifies collections, writes output, or performs validation. Moving continue by one line can change which of those actions occur.
Using Continue in a Python For Loop
A for loop obtains values from an iterable, such as a list, string, or range. When it reaches continue, Python requests the next value from the loop’s iterator.
This example skips one number:
for number in range(1, 6):
if number == 3:
continue
print(number)
1
2
4
5
When number is 3, the print call is still below continue, so it does not run. The loop itself remains active and proceeds with 4.
A more realistic use is filtering records before processing them. Suppose imported names may contain blank strings:
raw_names = [" Ada ", "", " ", "Grace"]
clean_names = []
for raw_name in raw_names:
name = raw_name.strip()
if not name:
print("Skipped blank name")
continue
clean_names.append(name)
print("Accepted:", name)
print(clean_names)
Accepted: Ada
Skipped blank name
Skipped blank name
Accepted: Grace
['Ada', 'Grace']
For each value, the loop:
- Removes surrounding whitespace.
- Checks whether any text remains.
- Reports and skips blank values.
- Adds valid names to
clean_names.
The append and the accepted message do not run for rejected input. This arrangement keeps the valid path aligned at the main indentation level, which becomes useful when processing code has several steps.
continue also works well when validation can fail for several independent reasons:
entries = ["18", "-2", "unknown", "0", "35"]
for entry in entries:
if not entry.isdigit():
print("Invalid text:", entry)
continue
age = int(entry)
if age <= 0:
print("Invalid age:", age)
continue
print("Accepted age:", age)
Accepted age: 18
Invalid text: -2
Invalid text: unknown
Invalid age: 0
Accepted age: 35
Here, "-2".isdigit() is false because the string contains a minus sign, so that value follows the invalid-text branch. Each rejection prevents acceptance, while the first check also prevents conversion of unsuitable text.
This pattern is helpful for input processing because each check sits next to its response. For experiments with small loops, the Python REPL makes it easy to change one condition and observe the result immediately.
If a loop only selects values without logging, mutation, or other side effects, a comprehension may be shorter:
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [number for number in numbers if number % 2 == 0]
print(even_numbers)
[2, 4, 6]
The Python comprehensions guide explains that filtering form in more detail. Keep the ordinary loop when rejection needs explanation, several checks must run, or processing has visible effects.
Using Continue in a Python While Loop
A while loop repeats while its condition remains true. Unlike a typical for loop, it often depends on code in the body to update the state used by that condition.
That makes update placement important:
number = 0
while number < 5:
number += 1
if number == 3:
continue
print(number)
1
2
4
5
The state update, number += 1, happens before the possible continue. On the third cycle, Python changes number from 2 to 3, reaches continue, and checks number < 5 again. The loop can still reach 5 and finish.
The execution around the skipped value is:
| Cycle | Value after update | Does continue run? | Is print reached? |
|---|---|---|---|
| 2 | 2 | No | Yes |
| 3 | 3 | Yes | No |
| 4 | 4 | No | Yes |
The dangerous arrangement puts the update after continue:
number = 0
while number < 5:
if number == 3:
continue
print(number)
number += 1
This code prints 0, 1, and 2. Once number becomes 3, continue repeatedly bypasses number += 1. The condition number < 5 remains true, so the loop does not terminate. Do not run this version unchanged: after printing 0, 1, and 2, it loops forever without further output.
In a while loop, check every path to continue. If one path skips the update needed to make the condition false, the loop can repeat forever.
A safe input-processing loop can update its position before validation:
responses = ["", " yes ", "later", "no"]
index = 0
while index < len(responses):
response = responses[index].strip().lower()
index += 1
if not response:
print("Ignored empty response")
continue
if response not in {"yes", "no"}:
print("Ignored unknown response:", response)
continue
print("Recorded:", response)
Ignored empty response
Recorded: yes
Ignored unknown response: later
Recorded: no
Every path advances index before it can continue. The loop therefore examines each entry exactly once.
Another safe design is to keep the update in one unavoidable place. Sometimes that means replacing continue with an if guard:
number = 0
while number < 5:
number += 1
if number != 3:
print(number)
1
2
4
5
For a short body, the guard is easy to read and removes the control transfer. For a longer body with several rejection conditions, early continue statements can make the valid path clearer. The choice is about control-flow clarity, not preference for one keyword.
Continue in Nested Loops
In nested loops, continue affects the nearest enclosing loop. If it appears inside the inner loop, it starts the next inner-loop iteration. The outer loop remains on its current iteration.
for row in range(1, 3):
print("row", row)
for column in range(1, 4):
if column == 2:
continue
print("cell", row, column)
row 1
cell 1 1
cell 1 3
row 2
cell 2 1
cell 2 3
For row == 1 and column == 2, control moves to the next column. It does not move to row == 2. The same rule applies during the second outer iteration.
Python has no special continue outer statement. When a condition found inside an inner loop should skip the rest of the outer iteration, restructure the code so the outer loop executes its own continue. A flag is one direct option:
records = [
["Ada", "Python"],
["Grace", ""],
["Linus", "C"],
]
for record in records:
has_blank_field = False
for field in record:
if field == "":
has_blank_field = True
break
if has_blank_field:
print("Skipped:", record)
continue
print("Accepted:", record)
Accepted: ['Ada', 'Python']
Skipped: ['Grace', '']
Accepted: ['Linus', 'C']
The inner break stops checking fields after it finds a blank. Execution then returns to the outer body. The outer continue skips acceptance for that record.
For a simple test, any() can remove the inner control flow:
records = [
["Ada", "Python"],
["Grace", ""],
["Linus", "C"],
]
for record in records:
if any(field == "" for field in record):
print("Skipped:", record)
continue
print("Accepted:", record)
Accepted: ['Ada', 'Python']
Skipped: ['Grace', '']
Accepted: ['Linus', 'C']
Both versions make the target loop visible: the continue is located directly inside the outer for, so it advances that loop.
Continue vs Break vs Pass
continue, break, and pass have different jobs. A plain if guard can sometimes avoid a control statement altogether.
| Construct | What it does | What runs next |
|---|---|---|
continue | Skips the remaining body of the current iteration | The next cycle of the nearest loop |
break | Terminates the nearest loop | The first statement after that loop |
pass | Performs no operation | The following statement in normal order |
if guard | Runs a block only when its condition is true | Normal execution after the conditional |
This example shows continue and break together:
for number in range(1, 7):
if number == 2:
continue
if number == 5:
break
print(number)
print("done")
1
3
4
done
At 2, continue advances the loop, so later values are still considered. At 5, break ends the loop, so 6 is never considered.
pass does not skip an iteration:
for number in range(1, 4):
if number == 2:
pass
print(number)
1
2
3
In the indented block form shown here, Python requires a nonempty suite after the if. pass satisfies that syntax requirement but changes no control flow. Execution continues to print(number).
An if guard can express the earlier skip-one-value example without continue:
for number in range(1, 4):
if number != 2:
print(number)
1
3
Use a guard when the conditional body stays short. Use continue when rejecting a value early prevents a large valid path from becoming deeply indented.
Loop else clauses add one precise distinction. The else suite runs if the loop finishes without executing break. A continue does not suppress it:
for number in range(3):
if number == 1:
continue
print(number)
else:
print("completed")
0
2
completed
Replace that continue with break, and the else suite would not run.
Common Continue Mistakes and Better Patterns
These mistakes usually come from losing track of which statement owns the control flow:
- Using
continueoutside a loop. It must be syntactically nested inside afororwhileloop. A function or class defined inside a loop creates a separate body, so placingcontinueinside that definition is still invalid. - Treating
continueas part ofif. The condition may decide whether it executes, butcontinueadvances the nearest loop. - Skipping a required
whileupdate. Move the update before any path that can continue, or restructure the body so the update cannot be bypassed. - Expecting an inner
continueto advance an outer loop. Put the outer decision in the outer loop, often with a flag,any(), or a helper function. - Writing statements after an unconditional
continue. Those statements cannot run. Delete them or correct the branch structure. - Using
continuefor a tiny conditional body. A plain guard can state the rule more directly. - Replacing side-effecting loops with comprehensions. Comprehensions are a good fit for producing collections. Logging, reporting validation failures, and updating several pieces of state usually read better in a normal loop.
Another advanced case involves try and finally. If continue transfers control out of a try, its finally suite runs before the next iteration begins:
for number in range(3):
try:
if number == 1:
continue
print("work", number)
finally:
print("cleanup", number)
work 0
cleanup 0
cleanup 1
work 2
cleanup 2
The work line is skipped for 1, but its cleanup line still appears. Code that releases a resource or restores state in finally therefore keeps running when the loop continues.
These details belong beside other control-flow fundamentals in a structured Python learning roadmap. They also explain several entries in the guide to common Python mistakes: the syntax is small, but the position of one statement can change termination, nesting, and cleanup behavior.
Where the Books Fit
If continue, nested loops, validation, and loop else still require deliberate tracing, Python in Three Months develops that control-flow skill through longer exercises and interview-style examples. Practise by predicting each printed line before running the code, then change one continue to break or a guard and trace the result again.
Frequently asked questions
What does continue do in Python?
The continue statement skips the unexecuted remainder of the current loop iteration. Execution then begins the next cycle of the nearest enclosing for or while loop.
What is the difference between continue and break in Python?
Continue advances the nearest loop to its next iteration. Break terminates the nearest loop completely, so no later iterations run.
Can continue be used outside a loop in Python?
No. A continue statement must be syntactically inside a for or while loop, and placing it inside a nested function or class does not satisfy that requirement.
Can continue cause an infinite while loop?
Yes. An infinite loop can occur when continue repeatedly skips the statement that updates the while loop's condition. Perform the required state update before the possible continue.
Does continue skip every level of a nested loop?
No. Continue affects only the nearest enclosing loop. An inner-loop continue advances the inner loop and does not automatically skip the current iteration of an outer loop.