Python’s continue
keyword functions as a statement that controls the flow of a loop. It allows you to skip code in a loop for the current iteration and jump immediately to the next one. It’s used exclusively in for
and while
loops, letting you control the flow of execution, bypass specific conditions, and continue processing in a structured and predictable way.
By the end of this tutorial, you’ll understand that:
continue
doesn’t affect the else
clause of a loop.continue
incorrectly may result in skipping necessary code.continue
in a function or class that’s nested in a loop.continue
executes the same instructions as reaching the end of a loop.Armed with this knowledge, you’ll be able to confidently write loops using continue
and expand your skills as a Python programmer.
Get Your Code: Click here to download the free sample code that shows you how to skip ahead in loops with Python’s continue keyword .
Take the Quiz: Test your knowledge with our interactive “Skip Ahead in Loops With Python's Continue Keyword” quiz. You’ll receive a score upon completion to help you track your learning progress:
Python’scontinue
Keyword
Loops are control flow statements used to perform operations repeatedly a certain number of times. In a normal loop, the loop body runs from start to finish, with the number of iterations controlled by the type of loop:
for
loop runs a specific number of times and is usually used to process a collection of data.while
loop runs as long as a specific condition evaluates to True
. When the condition evaluates to False
, the loop ends.In both cases, you may find it useful to stop the execution of the loop body and move to the next iteration. The way to do that is with the continue
keyword.
In any loop, continue
stops the code currently executing, and jumps immediately back to the top of the loop, skipping to the next iteration.
for
and while
Loops
In a for
loop, continue
moves the iterator to the next item to be processed. If no other items are available, then the loop ends.
Assume you have the following for
loop that computes the sum of all numbers in a list:
This works fine, but what if you want to add only the positive numbers, ignoring all the negative ones? You can modify this loop to add only positive numbers using continue
:
In this case, since Python executes continue
only when the number is less than zero, it doesn’t add those numbers to total
.
You’ve seen how the continue
statement works in a for
loop—now you’ll see it working similarly in a while
loop.
In a while
loop, continue
transfers control back to the condition at the top of the loop. If that condition is True
, then the loop body will run again. If it’s False
, then the loop ends.
Consider the following while
loop. It leverages Python’s walrus operator to get user input, casts it to an int
, and adds the number to a running total. The loop stops when the user enters 0
:
Again, you only want to add the positive numbers that your users enter, so you modify the loop using continue
:
You can copy the code and try it out. When you run the script, Python keeps prompting you for input until you enter 0
:
The loop adds all the positive numbers you enter. It ignores negative numbers by skipping to the next iteration using continue
before adding the input to total
. When you enter 0
, the script ends and prints the total of all positive numbers.
Whether you’re using a for
loop or a while
loop, the continue
statement immediately ends the current flow of execution and moves to the next iteration of the loop. If there are no further iterations, because a for
loop has exhausted its iterator or a while
loop’s condition evaluates to False
, then the loop ends.
else
Clause
The else
clause, when applied to a for
or while
loop, runs after the loop finishes its last iteration. This occurs even if the last iteration was skipped due to a continue
statement.
Assume you have a for
loop that prints the squares of all even numbers, followed by the word Done
in an else
clause:
This results in the following output:
The last iteration of the loop occurs when number
is 9
, which is the last number returned by range()
in the loop. That iteration is skipped by continue
on line 3, and control moves to the else
clause to complete execution of the loop.
The else
clause runs even in a while
loop:
Here, you do essentially the same as before, only you start by assigning number
to 0
, and then increment it inside the loop body. The condition your while
loop keeps checking is whether number
is less than 9
.
Just like before in the for
loop version of this code, you check whether the current value of number
is odd using the modulo operator. If it’s odd, then you execute continue
. If it’s even, then you square the number and print that value.
This results in the same output as when you ran the for
loop earlier:
In both loops, when Python executes the continue
statement, it skips the rest of the current iteration. Each loop ends normally, so the else
clause runs after the final iteration.
Note: While continue
doesn’t prevent code in a loop’s else
clause from running, the break
keyword does!
Now you know the most important parts of how continue
works to control both for
and while
loops. You also know that it doesn’t impact the execution of any else
clauses that may be associated with your loops.
Next, you’ll see some practical examples and use cases, which will be a bit more complex than the previous code examples. Feel free to continue reading (pun intended), but you can also stop here if you’re comfortable with the fundamentals.
Practical ExamplesIn the previous section, you learned the basics of using continue
in loops. Now you’ll explore two practical examples that show how this statement can simplify loop logic and make your code more efficient in real-world scenarios.
Using continue
in a for
loop can be helpful when processing input, allowing you to skip certain values that don’t contribute to the final goal. Here’s an example of that, from a solution to the 2022 Advent of Code Challenge, Day 7 puzzle.
Note: Advent of Code is a yearly puzzle event that starts on December 1 and ends on December 25. Every day over that period, two related puzzles are published, which can be solved in any way you see fit. Real Python writers and staff have participated in the contest over the past several years, challenging ourselves and each other while honing and learning new skills.
In the Day 7 challenge, you’re given an input file containing the commands and output for a terminal session on a fictional computer. Each line of your input file is either a command prefaced by a shell prompt ($
), or the output of that command. Your task is to reconstruct the file system for this computer based on that information.
There are only two commands you need to process. The cd
command changes directories and needs to analyze its arguments but produces no output. The ls
command produces a list of files in the current directory, but requires no further analysis.
The code snippet below outlines one possible solution to this challenge using a for
loop. It isn’t complete because it omits several parts, but it serves as a high-level example that highlights how the continue
statement can be useful here:
On line 7, using continue
allows the code to maintain a uniform organized structure, clearly processing each command as it appears. Input lines that don’t need additional work are skipped without introducing special cases or other complications that could affect readability.
One great use of continue
in a while
loop appears in Dijkstra’s algorithm, which is used to find the shortest path between two nodes in a graph.
A graph is a set of vertices—also called nodes—connected by edges, also known as paths. Each path has a cost associated with it, representing the cost of traveling from one node to another. Dijkstra’s algorithm uses these costs to calculate the lowest total-cost path from a starting node to every other node, including the desired final node.
To do this, the algorithm first marks the final distance to the starting node as 0, and the final distance to all other nodes as infinity. It then identifies all the nodes connected to the starting node and calculates the cost to get to each connected node using the cost of the path to each node.
It then marks the starting node as having been visited already, so it doesn’t process it again, and adds all the other nodes to a list for processing.
The algorithm then enters a while
loop, where it picks the next node to check—current_node
—as the one with the lowest-cost path to it. It checks all the nodes connected to current_node
, skips any that have already been visited, and calculates the cost to get to them. It then marks current_node
as visited and returns to the top of the loop. The process ends when all the nodes have been visited.
Assuming that the nodes to be checked are in a structure called node_list
, the key part of Dijkstra’s algorithm might look something like this:
The continue
statement on line 9 is the key to this algorithm. Without it, you’d calculate distances to nodes you’ve already come from, which have a lower cost to reach.
Now that you’ve seen two practical examples, you’ll learn about the potential problems and pitfalls you may encounter when using continue
.
The continue
statement is a useful tool for controlling the flow of your loops, but it comes with some risks. Misusing continue
can introduce subtle, hard-to-find bugs or make your code harder to read and maintain. In this section, you’ll learn about the common mistakes to avoid when using continue
in your loops.
continue
and break
Loops can also contain the break
keyword, which ends the loop immediately. No further iterations are executed, and—crucially—any else
clauses are skipped. It’s important to make sure you’re using the correct functionality for your program.
Using continue
ends the execution of the current loop iteration and returns control to the top of the loop. This means any code after continue
is skipped. If that code needs to run, then continue
can introduce hard-to-find bugs, especially in a while
loop.
Here’s a contrived example that demonstrates the issue using a while
loop that prints the squares of even numbers from 1 to 10:
This loop requires number
to be incremented on every iteration. However, the if
statement on line 4 prevents this when the number is odd, causing the loop to continue without incrementing number
. This results in an infinite loop.
If you have nested loops, which you create by placing one loop inside another, then continue
will only jump to the next iteration of the innermost loop that contains the continue
statement.
Here’s an example that demonstrates this issue using nested for
loops to print multiplication tables for even numbers:
Both continue
statements on lines 5 and 8 jump to the next iteration of the for inner_number
loop on line 2. This happens even though the conditional on line 7 uses outer_number
. Neither statement affects the for outer_number
loop on line 1.
When you use continue
indiscriminately, it can make your code less readable and understandable. For example, take another look at the code from earlier that demonstrated how to use continue
:
This code is arguably easier to read by refactoring the conditional on line 4 to avoid using continue
entirely:
You could also argue that a more Pythonic way to add values is by calling sum()
with a generator expression as an argument to filter the positive values:
In most cases, you can rewrite confusing or hard-to-understand loops without using continue
.
Now you know what to look for when writing code with continue
and how to use it in practical code to solve real-world problems. In the next section, you’ll peer under the hood to see how the Python interpreter actually executes the continue
statement. Hold on—it’s going to get bumpy.
Until now, you’ve focused on how to use the continue
statement effectively in your code. But have you ever wondered what Python actually does when it encounters continue
inside a loop? This section pulls back the curtain to explore how Python parses and executes your code, helping you understand what’s really going on when your loops skip ahead.
As you learned earlier, continue
only works inside a loop—it has no function outside a loop and will be flagged as a syntax error if it’s not used inside a loop. The official Python documentation for continue
describes how this works:
continue
may only occur syntactically nested in afor
orwhile
loop, but not nested in a function or class definition within that loop [emphasis added]. It continues with the next cycle of the nearest enclosing loop. (Source)
The italicized portion requires some explanation, which is best done in code:
The continue
statement on line 5 is flagged as a SyntaxError
because while it’s nested in an enclosing while
loop, it’s also nested in the function check_even()
.
Each function defined in Python is an independent block of code, separate from any code surrounding it. Additionally, when you define a function, Python doesn’t execute the code in the function body. That only happens when you call the function.
When a function is called, Python creates an execution context where the function runs. This context is separate from the execution context of the caller. If Python tried to execute the continue
statement within the function’s execution context, it wouldn’t be able to connect it to the containing loop in the caller’s execution context. Therefore, Python flags this as a syntax error and doesn’t run the code.
In essence, check_even()
isn’t aware it’s being called from inside the for
loop on line 1, and therefore can’t directly influence its flow.
Here’s the code refactored to be syntactically correct:
This code removes continue
from the function while retaining the purpose of check_even()
in the loop.
However, defining the function multiple times inside the loop in the first place isn’t good practice and is shown here only to illustrate this issue. The best approach would be to move the function definition outside of the loop entirely:
Later in the same documentation, you’ll find the following passage:
When
continue
passes control out of atry
statement with afinally
clause, thatfinally
clause is executed before really starting the next loop cycle. (Source)
In other words, a continue
statement in a try-except
block will not prevent any code in an associated finally
block from being executed, even if continuing the loop transfers control out of a try
or except
block. This is similar to the action of continue
when used in a loop with an else
clause.
This may be clearer with another code example:
This for
loop generates two numbers, 0
and 1
. It prints a message indicating which iteration is being executed, then checks the value of number
, taking one of two actions based on that value:
In the first iteration, when number
is 0
, it prints a message that this is the normal flow of execution and then exits the try
block normally. Python then executes the finally
block.
In the second iteration, when number == 1
evaluates to True
, the code prints a message and executes continue
. This exits the try
block but still runs the finally
block before moving back to the beginning of the loop. Because of continue
, this iteration skips the final call to print()
on line 17.
The continue
statement jumps to the start of the loop, but it doesn’t prevent execution of the finally
block. The code in finally
always runs, whether you exit a try
block normally, with continue
, or when Python raises an exception and moves to except
.
Now that you’ve read the relevant parts of Python’s documentation and experienced what they mean with code examples, you’ll delve into exactly what the Python interpreter does when it encounters a continue
statement in your code. Get ready to go deep into the inner workings of the Python interpreter.
The Real Python book CPython Internals: Your Guide to the Python 3 Interpreter explores in depth how the Python 3 interpreter parses, analyzes, and executes your code. As part of the book, author Anthony Shaw also developed the instaviz
module, which shows code objects, abstract syntax trees, and the disassembled Python opcodes and arguments for the compiled code.
Note: This section won’t attempt to explain the intricacies of how the CPython interpreter reads, converts, and compiles your Python code. For a deeper understanding of the concepts discussed here, you’re encouraged to read CPython Internals.
It’s the disassembly of the compiled Python code as presented by instaviz
that best shows how the continue
statement works to modify a loop. First, you’ll analyze the code below, which demonstrates how a for
loop works without continue
. This example uses a modified version of the code sample you saw at the beginning of this tutorial:
The code on lines 7 and 8 is commented out initially to analyze the loop without continue
. This keeps the line numbers consistent when you compare the analysis of the initial code with the analysis that includes continue
later.
So, what’s happening here? The instaviz.show()
function on line 13 starts a WSGIRefServer()
web server on http://localhost:8080/
, using the Bottle
library to format and display results in a web page. That page shows the properties of the Python code object, the abstract syntax tree (AST) for that code, and the disassembly for the code.
While the AST and code object metadata are interesting to see, it’s the code disassembly that best shows how continue
works. A condensed and rearranged version of the code disassembly is shown below:
This reformatted table shows how the Python 3.13 interpreter analyzes the code in the listing above and turns it into internal bytecode. Here’s how to read each column:
Line Number: Each value aligns with the corresponding line number in the code. Any instructions without a line number belong to the previously listed line.
Operation Name: Each name represents a basic operation that the CPython interpreter recognizes. Your Python code is compiled into these basic instructions as part of the parsing and analysis phase. A complete list of these operations, along with how they’re generated and what they do, is detailed in the CPython Internals book.
Index Offset: Each operation is represented by a multi-byte code (not shown), whose location appears in the column. Code that alters the flow of execution jumps to these numbered locations.
Resolved Arg Value: Each argument shows the human-readable value passed to the opcode, such as variable names or constants.
Looking at the code and this table, you can see correlations between them. Orient yourself by looking at the Index Offset column and identify the relevant lines based on the numbers shown there:
total
variablefor
loop on line 7
range
generatorrange
number
iterator variabletotal
variable
total
and number
+=
binary operation between the two valuestotal
JUMP_BACKWARD
operation to go back to the next iteration at offset 30for
loop has exhausted the iteratorrange()
generatortotal
to be returned at the end of the functiontotal
Note that these steps may vary slightly depending on your Python version, as the bytecode generated can change between different versions.
Now you can uncomment the two lines that were previously commented out to add the continue
statement back in:
The following disassembly table is generated for this code:
Line Number Operation Name Index Offset Resolved Arg Value 3 RESUME 0 0 4 LOAD_CONST 2 0 STORE_FAST 4 total 6 LOAD_GLOBAL 6 range LOAD_CONST 16 -10 LOAD_CONST 18 10 CALL 20 2 GET_ITER 28 None FOR_ITER 30 Offset 64 STORE_FAST 34 number 7 LOAD_FAST 36 number LOAD_CONST 38 0 COMPARE_OP 40 < POP_JUMP_IF_FALSE 44 52 8 JUMP_BACKWARD 48 Offset 30 9 LOAD_FAST_LOAD_FAST 52 (‘total’, ‘number’) BINARY_OP 54 13 STORE_FAST 58 total JUMP_BACKWARD 60 Offset 30 10 END_FOR 64 None POP_TOP 66 None 11 LOAD_FAST 68 total RETURN_VALUE 70 NoneThe only changes in the code listing are on lines 8 and 9, so it’s no surprise that the corresponding differences in the disassembly appear at index offsets 36 through 48:
if
statement by loading the value of number
.0
.<
, the less-than operator.number < 0
is False
, using POP_JUMP_IF_FALSE
.continue
statement on line 9 by transferring control to offset 30, which starts the next iteration of the for
loop.Note that there are two operations that use JUMP_BACKWARD
to jump to the same place:
continue
statement at line 8Both operations jump to the top of the for
loop at offset 30. This shows that the continue
statement behaves at a low level exactly like reaching the end of a loop iteration. Both events result in the same action—namely, returning to the top of the loop to start the next iteration. This explains why continue
doesn’t impact the execution of else
or finally
clauses: it behaves the same as reaching the end of the loop.
Congratulations! You made it through the tutorial. Maybe you skipped some parts and had to loop back. That’s okay! The important thing is that you continued to the finish. Come back and restart any time.
In this tutorial, you’ve learned how to:
continue
to move to the next iteration of a for
or while
loop, skipping the rest of the loop body for that iterationcontinue
statement to real-world coding taskscontinue
with the break
keywordcontinue
is implemented and how it affects control flowWith this knowledge, you can now confidently and effectively use continue
to make your Python loops even more powerful.
Get Your Code: Click here to download the free sample code that shows you how to skip ahead in loops with Python’s continue keyword .
Frequently Asked QuestionsNow that you have some experience using the continue
statement in Python loops, you can use the questions and answers below to check your understanding and recap what you’ve learned.
These FAQs are related to the most important concepts you’ve covered in this tutorial. Click the Show/Hide toggle beside each question to reveal the answer.
You use the continue
statement in Python to skip the rest of the code inside a loop for the current iteration and move directly to the next iteration.
In a for
loop, the continue
statement skips the remaining code in the loop body for the current iteration and jumps to the next item in the iterator. If no items are left, then the loop ends.
Yes, you can use continue
in a while
loop to skip the remaining code in the loop body and return control to the loop’s condition at the top for the next iteration.
When you use continue
in a loop with an else
clause, the else
block still runs after the loop finishes all its iterations, even if some iterations were skipped with continue
.
A common mistake is confusing continue
with break
, which exits the loop entirely. Another mistake is skipping necessary code after continue
, which can cause logic errors or infinite loops.
Take the Quiz: Test your knowledge with our interactive “Skip Ahead in Loops With Python's Continue Keyword” quiz. You’ll receive a score upon completion to help you track your learning progress:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4