Demo — Sample data. Import and AI enrichment are disabled. jamesbriscoe.dev
120 articles
WA SW DEVELOPER - Tips & Tricks · realpython.com · 08 May 2025
Python continue
SW Developer #python #cicli

AI Summary
Python’s continue permette di saltare il corpo di un ciclo for o while e procedere al prossimo iterazione, senza interrompere il flusso del programma. È utile per gestire condizioni specifiche all'interno di un ciclo.
Key Points
  • Python’s continue permette di saltare il corpo di un ciclo for o while e procedere al prossimo iterazione
  • Il continue è utilizzato per gestire condizioni specifiche all'interno di un ciclo
Full text

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:
- Executing
continue
doesn’t affect theelse
clause of a loop. - Using
continue
incorrectly may result in skipping necessary code. - You can’t use
continue
in a function or class that’s nested in a loop. - On a bytecode level,
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:
Interactive Quiz
Skip Ahead in Loops With Python's continue KeywordTest your understanding of Python's continue keyword, which allows you to skip code in a loop for the current iteration and jump immediately to the next one.
Python’s continue
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:
- A
for
loop runs a specific number of times and is usually used to process a collection of data. - A
while
loop runs as long as a specific condition evaluates toTrue
. When the condition evaluates toFalse
, 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.
Understanding Its Behavior in 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:
total = 0
for number in range(-10, 10):
total += number
print(total)
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
:
total = 0
for number in range(-10, 10):
if number < 0:
continue
total += number
print(total)
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
:
sum_whole_numbers.py
print("Enter one whole number per input.")
print("Type 0 to stop and display their sum:")
total = 0
while (user_int := int(input("+ "))) != 0:
total += user_int
print(f"{total=}")
Again, you only want to add the positive numbers that your users enter, so you modify the loop using continue
:
sum_whole_numbers.py
print("Enter one whole number per input.")
print("Type 0 to stop and display their sum:")
total = 0
while (user_int := int(input("+ "))) != 0:
if user_int < 0:
continue
total += user_int
print(f"{total=}")
You can copy the code and try it out. When you run the script, Python keeps prompting you for input until you enter 0
:
$ python sum_whole_numbers.py
Enter one whole number per input.
Type 0 to stop and display their sum:
+ 1
+ 2
+ -100
+ 0
total=3
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.
Interacting With the 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:
1for number in range(1, 10):
2 if number % 2 == 1:
3 continue
4
5 print(number ** 2)
6
7else:
8 print("Done")
This results in the following output:
4
16
36
64
Done
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:
1number = 0
2
3while number < 9:
4 number += 1
5
6 if number % 2 == 1:
7 continue
8
9 print(number ** 2)
10
11else:
12 print("Done")
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:
4
16
36
64
Done
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 Examples
In 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.
Solving an Advent of Code Challenge
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:
aoc_2022_d7.py
1# ...
2
3def parse(lines):
4 for line in lines:
5 line_parts = line.split()
6 if line_parts[1] == "ls":
7 continue
8 elif line_parts[1] == "cd":
9 change_directory(line_parts)
10 else:
11 process_file(line_parts)
12
13with open("input.txt") as input_file:
14 input_file_lines = [
15 input_file_line.strip()
16 for input_file_line in input_file.readlines()
17 ]
18
19parse(input_file_lines)
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.
Skipping Visited Nodes in Dijkstra’s Algorithm
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:
1# While there are still nodes to check
2while len(node_list) > 0:
3
4 # Get the node with the minimum distance
5 current_node = remove_minimum_node(node_list)
6
7 # Skip already visited nodes
8 if current_node.visited:
9 continue
10
11 # Mark the node as visited
12 current_node.visited = True
13
14 # Check neighbors and calculate distance
15 # ...
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
.
Common Pitfalls
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.
Confusing 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.
Skipping Necessary Code
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:
1number = 1
2
3while number <= 10:
4 if number % 2 == 1:
5 continue
6
7 print(number ** 2)
8 number += 1
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.
Getting Stuck in Nested Loops
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:
1for outer_number in range(1,11):
2 for inner_number in range(1,11):
3
4 if inner_number % 2 == 1:
5 continue
6
7 if outer_number % 2 == 1:
8 continue
9
10 print(outer_number * inner_number)
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.
Reducing Readability
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
:
1total = 0
2
3for number in range(-10, 10):
4 if number < 0:
5 continue
6 total += number
7
8print(total)
This code is arguably easier to read by refactoring the conditional on line 4 to avoid using continue
entirely:
1total = 0
2
3for number in range(-10, 10):
4 if number > 0:
5 total += number
6
7print(total)
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:
total = sum(number for number in range(-10, 10) if number > 0)
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.
Under the Hood
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.
Understanding the Official Documentation
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:
1>>> for number in range(10):
2...
3... def check_even(number):
4... if number % 2 == 0:
5... continue
6... else:
7... return number
8...
9... print(check_even(number))
10...
11 File "<python-input-0>", line 5
12 continue
13 ^^^^^^^^
14SyntaxError: 'continue' not properly in loop
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:
1>>> for number in range(10):
2...
3... def check_even(number):
4... return number % 2 == 0
5...
6... if check_even(number):
7... continue
8... else:
9... print(number)
10...
111
123
135
147
159
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:
1>>> def check_even(number):
2... return number % 2 == 0
3...
4>>> for number in range(10):
5... if check_even(number):
6... continue
7... else:
8... print(number)
9...
101
113
125
137
149
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:
continue_finally.py
1for number in range(2):
2 try:
3 print(f"Iteration {number}: start of try block")
4
5 if number == 1:
6 print(f" Executing `continue` in iteration {number}...")
7 continue
8
9 print(f" Normal flow in iteration {number}...")
10
11 except Exception as e:
12 print(f"Iteration {number}: Exception: {e}")
13
14 finally:
15 print(f"Iteration {number}: finally block")
16
17 print(f"Iteration {number}: rest of loop body", end="\n\n")
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
is0
, it prints a message that this is the normal flow of execution and then exits thetry
block normally. Python then executes thefinally
block. -
In the second iteration, when
number == 1
evaluates toTrue
, the code prints a message and executescontinue
. This exits thetry
block but still runs thefinally
block before moving back to the beginning of the loop. Because ofcontinue
, this iteration skips the final call toprint()
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.
Inspecting Disassembled Bytecode
The Real Pytho

0%