PythonConditional Statements and LoopsPython loop control
How does the `continue` statement work?
Question 55 of 88 · Updated
On this page
- 1. Using continue in a for loop
- 2. Using continue in a while loop
- 3. continue, break and pass compared
- 4. Continue affects only the innermost enclosing loop
- 5. Continue respects finally cleanup
- 6. Continue and context managers
- 7. Continue does not suppress a loop else clause
- 8. Practical example: skip invalid input while keeping a rejection report
- 9. Continue does not undo earlier operations
- 10. What happens to the iterator?
- 11. Where continue is legal
- 12. When to use a skip-first style
- 13. Common mistakes
- Frequently asked questions
- Does continue skip the entire loop?
- Can continue be used in a while loop?
- What happens if continue is reached on the last iteration?
- Does finally execute before the next iteration?
- Does continue make a loop faster?
- Interview-ready answer
- Official references
The continue statement skips the remaining ordinary statements in the current iteration of the innermost enclosing loop and transfers control to that loop's next-iteration mechanism. In a for loop, Python attempts to obtain the next item. In a while loop, Python evaluates the condition again.
Unlike break, continue does not intentionally end the loop. Unlike pass, it changes control flow. It is especially useful for rejecting invalid records, filtering items and keeping the main processing path readable.
The earlier loop, infinite-loop and break lessons introduce these ideas. This lesson focuses on the precise behavior of continue, including nested loops, cleanup, and the difference between skipping work and undoing work.
1. Using continue in a for loop#
PYTHONfor n in range(5): if n%2==0: continue print(n) print("done")
Output:
1
3
doneThe loop traverses 0, 1, 2, 3 and 4. For each even value, the if condition succeeds and continue skips the print statement inside the body. Odd values reach that statement.
| Current item | Even? | Action |
|---|---|---|
| 0 | Yes | Skip remaining body |
| 1 | No | Print 1 |
| 2 | Yes | Skip remaining body |
| 3 | No | Print 3 |
| 4 | Yes | Skip remaining body |
After consuming the final item, the loop attempts to obtain another item and finishes normally when the iterator is exhausted.
This diagram describes normal iteration without a loop else suite or pending cleanup. Continue is a statement with no argument; it is not a function.
2. Using continue in a while loop#
PYTHONi=0 while i<4: i+=1 if i==2: continue print(i)
Output:
1
3
4The increment happens before the skip condition. When i becomes 2, continue transfers control back to the while condition. The condition still permits another iteration, and the next increment changes i to 3.
Continue does not automatically increment a counter. If the only state update appears after a continue that is repeatedly reached, a while loop can become infinite.
For a finite loop, ensure that every repeating path makes progress or has an appropriate exit policy. In particular, inspect all continue paths when debugging a stalled counter. The previous infinite-loop lesson gives a more extensive treatment of termination and bounded repetition.
3. continue, break and pass compared#
| Statement | Effect on the current iteration | Effect on the loop |
|---|---|---|
| continue | Skips the remaining ordinary body | Attempts the next iteration |
| break | Skips the remaining ordinary body | Exits the innermost loop |
| pass | Does nothing | Execution proceeds to the following statement |
A continue may lead immediately to normal loop completion if no next item exists or if the while condition is false. It does not guarantee another body execution.
Pass is a syntactic no-op. It does not skip the rest of an iteration. If a pass statement is followed by another statement in the same suite, that following statement can still execute.
Return exits the enclosing function, not merely one iteration. Choose the statement that expresses the intended boundary of control transfer.
4. Continue affects only the innermost enclosing loop#
PYTHONfor row in range(2): for col in range(3): if col==1: continue print(row,col) print("row done")
Output:
0 0
0 2
row done
1 0
1 2
row doneThe continue is inside the inner loop. For each row, it skips column 1 and then the inner loop processes column 2. After normal completion of that inner loop, the outer body prints row done.
Python has no labeled continue statement that targets an arbitrary enclosing loop. If a condition should skip an outer iteration, place that decision at the outer loop's level, or extract inner processing into a helper that returns a clear result.
Be careful with indentation. Moving the same condition and continue to a different loop changes which repetition is affected.
5. Continue respects finally cleanup#
PYTHONfor n in [1,2]: try: print("visit",n) if n==1: continue print("work",n) finally: print("cleanup",n) print("done")
Output:
visit 1
cleanup 1
visit 2
work 2
cleanup 2
doneOn the first iteration, continue skips the ordinary work statement. The finally suite still executes before the pending transfer to the next iteration. On the second iteration, the work statement executes and cleanup follows normally.
This path assumes that the finally suite completes normally and that the continue leaves the associated try/finally construct. A cleanup exception can interrupt the transfer, and another permitted control transfer in cleanup can alter it.
Avoid using control-flow statements in finally suites to suppress an exception or obscure the intended outcome. Python versions may differ in warnings or restrictions concerning such constructs.
6. Continue and context managers#
PYTHONfrom contextlib import contextmanager @contextmanager def resource(n): print("open",n) try: yield finally: print("close",n) for n in range(2): with resource(n): if n==0: continue print("work",n)
Output:
open 0
close 0
open 1
work 1
close 1The first continue leaves the with suite, so the context manager's exit protocol executes before the next iteration. The second iteration completes its work and leaves the context normally.
The resource is managed separately for each iteration in this example. If the with statement surrounded the entire loop, its exit protocol would instead run when control left that enclosing with suite.
Use a suitable context manager or explicit cleanup when resources must be released reliably. Continue does not automatically clean up every object used in the loop; it only follows the relevant language-level control-transfer and resource-management rules.
7. Continue does not suppress a loop else clause#
PYTHONfor n in [1,2]: if n==1: continue print(n) else: print("exhausted")
Output:
2
exhaustedThe continue skips processing for the first value, but the loop eventually exhausts its input normally. Its else suite therefore executes.
A break from that loop would skip the else suite. A return or an exception that leaves the loop can also prevent normal completion. For a while loop, normal completion occurs when its condition becomes false.
The important distinction is that continue changes the current iteration, not the loop's normal-completion policy. A separate upcoming lesson discusses loop else in greater depth.
8. Practical example: skip invalid input while keeping a rejection report#
Suppose a batch contains text representations of nonnegative integer quantities. Some records may be malformed or contain negative values. Instead of ending the entire batch at the first invalid input, process valid values and record the positions of rejected entries.
PYTHONdef summarize(rows): total=0 rejected=[] for i,text in enumerate(rows): try: value=int(text) except ValueError: rejected.append(i) continue if value<0: rejected.append(i) continue total+=value return total,rejected print(summarize(["4","bad","-2","0","6"])) print(summarize([]))
Output:
(10, [1, 2])
(0, [])The string bad cannot be converted to an integer, so the ValueError branch records its zero-based position. The negative value -2 is syntactically valid integer text but fails the business rule. Both paths skip accumulation. The values 4, 0 and 6 contribute a total of 10.
The function assumes rows supplies strings and accepts the text formats supported by int. It deliberately catches only ValueError from conversion. A wrong input type can raise TypeError instead; such a failure is outside this example's input contract. A real ingestion system should define its accepted text formats, numeric bounds, rejection policy and audit requirements.
For n rows and r rejected entries, the loop uses O(n) iterations and O(r) auxiliary storage for the rejection indexes, under bounded-size conversion and arithmetic assumptions. Actual runtime also depends on text lengths, integer magnitudes and the cost of retrieving the input items.
This pattern is useful when invalid records may be skipped according to an explicit application policy. It is not appropriate when a single invalid record must cause the entire operation to fail. Do not silently discard errors in financial, safety-critical or transactional workflows.
9. Continue does not undo earlier operations#
PYTHONseen=[] for n in [1,2,3]: seen.append(n) if n==2: continue print(n) print(seen)
Output:
1
3
[1, 2, 3]The value 2 was appended before continue executed. Although the print was skipped, the earlier list mutation remains.
Continue is not a rollback operation. Side effects that occur before the statement, such as writing a record, modifying an object or incrementing a counter, are not automatically reversed.
Validate data before irreversible work when a rejected item should have no effect. If an operation must provide all-or-nothing semantics, use an appropriate transactional mechanism rather than relying on loop-control syntax.
10. What happens to the iterator?#
PYTHONit=iter([1,2,3]) for n in it: if n==1: continue print(n) print(list(it))
Output:
2
3
[]The first value was fetched and assigned to n before it was skipped. Continue does not return the value to the iterator or retry the same item. The for loop requests the next value and ultimately exhausts the iterator.
In a while loop, continue instead transfers to reevaluation of the header condition. Whether that leads to a new input item or repeats the same state depends on the program.
If the intended behavior is to retry the current operation, design an explicit retry mechanism with a suitable attempt budget. Do not assume continue automatically retries the current item.
11. Where continue is legal#
Continue must occur within an appropriate enclosing loop body. It cannot cross a nested function or class definition boundary to target a loop outside that definition.
Three independent compilation tests confirm SyntaxError for:
- A standalone continue outside a loop.
- A continue inside an if statement with no enclosing loop.
- A continue inside a nested function defined in a loop, when that function contains no loop of its own.
An if statement does not itself provide a target for continue. It simply provides a condition under which the surrounding loop's control transfer can occur.
Continue also works in asynchronous for loops in an appropriate async context. Asynchronous iteration and cancellation have additional protocol considerations and are covered separately.
12. When to use a skip-first style#
A skip-first condition can keep the main body less indented. For example, reject malformed entries near the top of a processing loop and continue before entering the main work.
For a small positive condition with a single action, an ordinary if suite may be just as clear. Prefer the structure that makes the accepted and rejected cases easy to understand. Avoid many scattered continue statements if they make the overall sequence of effects difficult to follow.
A comprehension with a filter is another option for a simple transformation or selection. A normal loop is often preferable when reporting rejected values, managing resources or handling exceptions.
Continue can avoid expensive work on rejected items, but it does not necessarily improve the asymptotic complexity. A loop that still examines all n records performs n traversal steps, even when most of them are skipped.
13. Common mistakes#
| Mistake | Better approach |
|---|---|
| Using continue when the entire loop should stop | Use break |
| Using pass to skip the rest of the body | Use continue |
| Updating a while-loop counter only after a possible continue | Ensure progress on every relevant path |
| Expecting an inner continue to skip an outer iteration | Move the decision to the appropriate loop |
| Assuming earlier effects are undone | Validate before mutation or use a transaction |
| Ignoring rejected records silently | Define a rejection policy and report failures when required |
| Expecting continue to suppress loop else | Remember that ordinary exhaustion still executes else |
Frequently asked questions#
Does continue skip the entire loop?#
No. It skips the remainder of the current iteration and resumes the iteration mechanism of the innermost enclosing loop.
Can continue be used in a while loop?#
Yes. It transfers control back to the condition test. Make sure any required state update is not skipped.
What happens if continue is reached on the last iteration?#
The loop attempts its normal next-iteration step. If the iterator is exhausted or the condition becomes false, the loop finishes normally.
Does finally execute before the next iteration?#
Yes, when the continue transfer exits an associated try/finally construct. The finally suite runs before the transfer completes, assuming it does not itself interrupt that transfer.
Does continue make a loop faster?#
It can avoid work on selected iterations. Actual performance depends on the amount of work skipped and the costs of iteration and condition testing.
Interview-ready answer#
Python's continue statement skips the remaining ordinary statements in the current iteration of the innermost enclosing loop. A for loop then requests the next item, whereas a while loop reevaluates its condition. Continue differs from break, which exits the loop, and pass, which does nothing. It does not undo previous side effects or prevent a loop else suite after normal completion. Applicable finally and context-manager cleanup still runs before the next iteration. Use continue for explicit skip conditions, and ensure that while-loop progress occurs even on skipped paths.
Official references#
- Python Language Reference — The continue statement
- Python Language Reference — The for statement
- Python Language Reference — The while statement
- Python Language Reference — The try statement
- Python Language Reference — The with statement
- Python Standard Library — contextlib
- Python Tutorial — More Control Flow Tools
Verification note: All nine fenced Python example groups were executed in independent namespaces on CPython 3.13.5 and matched their documented outputs. Three independent compilation tests raised the expected SyntaxError. The three fenced Mermaid diagrams were manually reviewed for the demonstrated paths; parser-level validation and live-site rendering were not performed. Official reference links are supplied under the authorized offline research exception; live documentation and the Supabase changelog were not checked.
References
- 1.Python Language Reference — The continue statementdocs.python.org
- 2.Python Language Reference — The for statementdocs.python.org
- 3.Python Standard Library — contextlibdocs.python.org
- 4.Python Tutorial — More Control Flow Toolsdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design