Basics Intermediate Advanced
aialgorithmsapibest-practicescareercommunitydatabasesdata-sciencedata-structuresdata-vizdevopsdjangodockereditorsflaskfront-endgamedevguimachine-learningnewsnumpyprojectspythonstdlibtestingtoolsweb-devweb-scraping

Skip Ahead in Loops With Python's continue Keyword
Table of Contents
Python’scontinue 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 infor andwhile 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
continuedoesn’t affect theelseclause of a loop. - Using
continueincorrectly may result inskipping necessary code. - You can’t use
continuein a function or class that’s nested in a loop. - On abytecode level,
continueexecutes the same instructions as reaching the end of a loop.
Armed with this knowledge, you’ll be able to confidently write loops usingcontinue 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’scontinue Keyword
Loops arecontrol 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
forloop runs a specific number of times and is usually used to process a collection of data. - A
whileloop 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 thecontinue 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 infor andwhile Loops
In afor loop,continue moves theiterator to the next item to be processed. If no other items are available, then the loop ends.
Assume you have the followingfor loop that computes the sum of all numbers in a list:
total=0fornumberinrange(-10,10):total+=numberprint(total)This works fine, but what if you want to add only thepositive numbers, ignoring all the negative ones? You can modify this loop to add only positive numbers usingcontinue:
total=0fornumberinrange(-10,10):ifnumber<0:continuetotal+=numberprint(total)In this case, since Python executescontinue only when the number is less than zero, it doesn’t add those numbers tototal.
You’ve seen how thecontinue statement works in afor loop—now you’ll see it working similarly in awhile loop.
In awhile loop,continue transfers control back to the condition at the top of the loop. If that condition isTrue, then the loop body will run again. If it’sFalse, then the loop ends.
Consider the followingwhile loop. It leverages Python’swalrus operator toget user input,casts it to anint, and adds the number to a running total. The loop stops when the user enters0:
sum_whole_numbers.pyprint("Enter one whole number per input.")print("Type 0 to stop and display their sum:")total=0while(user_int:=int(input("+ ")))!=0:total+=user_intprint(f"{total=}")Again, you only want to add the positive numbers that your users enter, so you modify the loop usingcontinue:
sum_whole_numbers.pyprint("Enter one whole number per input.")print("Type 0 to stop and display their sum:")total=0while(user_int:=int(input("+ ")))!=0:ifuser_int<0:continuetotal+=user_intprint(f"{total=}")You can copy the code and try it out. When yourun the script, Python keeps prompting you for input until you enter0:
$pythonsum_whole_numbers.pyEnter one whole number per input.Type 0 to stop and display their sum:+ 1+ 2+ -100+ 0total=3The loop adds all the positive numbers you enter. It ignores negative numbers by skipping to the next iteration usingcontinue before adding the input tototal. When you enter0, the script ends and prints the total of all positive numbers.
Whether you’re using afor loop or awhile loop, thecontinue statement immediately ends the current flow of execution and moves to the next iteration of the loop. If there are no further iterations, because afor loop has exhausted itsiterator or awhile loop’s condition evaluates toFalse, then the loop ends.
Interacting With theelse Clause
Theelse clause, when applied to afor orwhile loop, runs after the loop finishes its last iteration. This occurs even if the last iteration was skipped due to acontinue statement.
Assume you have afor loop that prints the squares of all even numbers, followed by the wordDone in anelse clause:
1fornumberinrange(1,10): 2ifnumber%2==1: 3continue 4 5print(number**2) 6 7else: 8print("Done")This results in the following output:
4163664DoneThe last iteration of the loop occurs whennumber is9, which is the last number returned byrange() in the loop. That iteration is skipped bycontinue on line 3, and control moves to theelse clause to complete execution of the loop.
Theelse clause runs even in awhile loop:
1number=0 2 3whilenumber<9: 4number+=1 5 6ifnumber%2==1: 7continue 8 9print(number**2)1011else:12print("Done")Here, you do essentially the same as before, only you start by assigningnumber to0, and then increment it inside the loop body. The condition yourwhile loop keeps checking is whethernumber is less than9.
Just like before in thefor loop version of this code, you check whether the current value ofnumber is odd using themodulo operator. If it’s odd, then you executecontinue. If it’s even, then you square the number and print that value.
This results in the same output as when you ran thefor loop earlier:
4163664DoneIn both loops, when Python executes thecontinue statement, it skips the rest of the current iteration. Each loop ends normally, so theelse clause runs after the final iteration.
Note: Whilecontinue doesn’t prevent code in a loop’selse clause from running, thebreak keyword does!
Now you know the most important parts of howcontinue works to control bothfor andwhile loops. You also know that it doesn’t impact the execution of anyelse 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 usingcontinue 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
Usingcontinue in afor 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 the2022 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. Thecd command changes directories and needs to analyze its arguments but produces no output. Thels 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 afor loop. It isn’t complete because it omits several parts, but it serves as a high-level example that highlights how thecontinue statement can be useful here:
aoc_2022_d7.py 1# ... 2 3defparse(lines): 4forlineinlines: 5line_parts=line.split() 6ifline_parts[1]=="ls": 7continue 8elifline_parts[1]=="cd": 9change_directory(line_parts)10else:11process_file(line_parts)1213withopen("input.txt")asinput_file:14input_file_lines=[15input_file_line.strip()16forinput_file_lineininput_file.readlines()17]1819parse(input_file_lines)On line 7, usingcontinue 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 ofcontinue in awhile loop appears inDijkstra’s algorithm, which is used to find the shortest path between two nodes in a graph.
Agraph 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 awhile 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 tocurrent_node, skips any that have already been visited, and calculates the cost to get to them. It then markscurrent_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 callednode_list, the key part of Dijkstra’s algorithm might look something like this:
1# While there are still nodes to check 2whilelen(node_list)>0: 3 4# Get the node with the minimum distance 5current_node=remove_minimum_node(node_list) 6 7# Skip already visited nodes 8ifcurrent_node.visited: 9continue1011# Mark the node as visited12current_node.visited=True1314# Check neighbors and calculate distance15# ...Thecontinue 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 usingcontinue.
Common Pitfalls
Thecontinue statement is a useful tool for controlling the flow of your loops, but it comes with some risks. Misusingcontinue 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 usingcontinue in your loops.
Confusingcontinue andbreak
Loops can also contain thebreak keyword, which ends the loop immediately. No further iterations are executed, and—crucially—anyelse clauses are skipped. It’s important to make sure you’re using the correct functionality for your program.
Skipping Necessary Code
Usingcontinue ends the execution of the current loop iteration and returns control to the top of the loop. This means any code aftercontinue is skipped. If that code needs to run, thencontinue can introduce hard-to-find bugs, especially in awhile loop.
Here’s a contrived example that demonstrates the issue using awhile loop that prints the squares of even numbers from 1 to 10:
1number=1 2 3whilenumber<=10: 4ifnumber%2==1: 5continue 6 7print(number**2) 8number+=1This loop requiresnumber to be incremented on every iteration. However, theif statement on line 4 prevents this when the number is odd, causing the loop to continue without incrementingnumber. This results in aninfinite loop.
Getting Stuck in Nested Loops
If you havenested loops, which you create by placing one loop inside another, thencontinue will only jump to the next iteration of the innermost loop that contains thecontinue statement.
Here’s an example that demonstrates this issue using nestedfor loops to print multiplication tables for even numbers:
1forouter_numberinrange(1,11): 2forinner_numberinrange(1,11): 3 4ifinner_number%2==1: 5continue 6 7ifouter_number%2==1: 8continue 910print(outer_number*inner_number)Bothcontinue statements on lines 5 and 8 jump to the next iteration of thefor inner_number loop on line 2. This happens even though the conditional on line 7 usesouter_number. Neither statement affects thefor outer_number loop on line 1.
Reducing Readability
When you usecontinue indiscriminately, it can make your code less readable and understandable. For example, take another look at the code from earlier that demonstrated how to usecontinue:
1total=0 2 3fornumberinrange(-10,10): 4ifnumber<0: 5continue 6total+=number 7 8print(total)This code is arguably easier to read byrefactoring the conditional on line 4 to avoid usingcontinue entirely:
1total=0 2 3fornumberinrange(-10,10): 4ifnumber>0: 5total+=number 6 7print(total)You could also argue that a morePythonic way to add values is by callingsum() with agenerator expression as an argument to filter the positive values:
total=sum(numberfornumberinrange(-10,10)ifnumber>0)In most cases, you can rewrite confusing or hard-to-understand loops without usingcontinue.
Now you know what to look for when writing code withcontinue 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 thecontinue statement. Hold on—it’s going to get bumpy.
Under the Hood
Until now, you’ve focused on how to use thecontinue statement effectively in your code. But have you ever wondered what Python actually does when it encounterscontinue 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 asyntax error if it’s not used inside a loop. The official Python documentation forcontinue describes how this works:
continuemay only occur syntactically nested in afororwhileloop,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>>>fornumberinrange(10): 2... 3...defcheck_even(number): 4...ifnumber%2==0: 5...continue 6...else: 7...returnnumber 8... 9...print(check_even(number))10...11 File"<python-input-0>", line512continue13^^^^^^^^14SyntaxError:'continue' not properly in loopThecontinue statement on line 5 is flagged as aSyntaxError because while it’s nested in an enclosingwhile loop, it’s also nested in the functioncheck_even().
Each function defined in Python is an independent block of code, separate from any code surrounding it. Additionally, when youdefine 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 thecontinue 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 asyntax error and doesn’t run the code.
In essence,check_even() isn’t aware it’s being called from inside thefor loop on line 1, and therefore can’t directly influence its flow.
Here’s the code refactored to be syntactically correct:
1>>>fornumberinrange(10): 2... 3...defcheck_even(number): 4...returnnumber%2==0 5... 6...ifcheck_even(number): 7...continue 8...else: 9...print(number)10...111123135147159This code removescontinue from the function while retaining the purpose ofcheck_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>>>defcheck_even(number): 2...returnnumber%2==0 3... 4>>>fornumberinrange(10): 5...ifcheck_even(number): 6...continue 7...else: 8...print(number) 9...101113125137149Later in the same documentation, you’ll find the following passage:
When
continuepasses control out of atrystatement with afinallyclause, thatfinallyclause is executed before really starting the next loop cycle. (Source)
In other words, acontinue statement in atry-except block will not prevent any code in an associatedfinally block from being executed, even if continuing the loop transfers control out of atry orexcept block. This is similar to the action ofcontinue when used in a loop with anelse clause.
This may be clearer with another code example:
continue_finally.py 1fornumberinrange(2): 2try: 3print(f"Iteration{number}: start of try block") 4 5ifnumber==1: 6print(f" Executing `continue` in iteration{number}...") 7continue 8 9print(f" Normal flow in iteration{number}...")1011exceptExceptionase:12print(f"Iteration{number}: Exception:{e}")1314finally:15print(f"Iteration{number}: finally block")1617print(f"Iteration{number}: rest of loop body",end="\n\n")Thisfor loop generates two numbers,0 and1. It prints a message indicating which iteration is being executed, then checks the value ofnumber, taking one of two actions based on that value:
In the first iteration, when
numberis0, it prints a message that this is the normal flow of execution and then exits thetryblock normally. Python then executes thefinallyblock.In the second iteration, when
number == 1evaluates toTrue, the code prints a message and executescontinue. This exits thetryblock but still runs thefinallyblock before moving back to the beginning of the loop. Because ofcontinue, this iteration skips the final call toprint()on line 17.
Thecontinue statement jumps to the start of the loop, but it doesn’t prevent execution of thefinally block. The code infinally always runs, whether you exit atry block normally, withcontinue, or when Python raises an exception and moves toexcept.
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 acontinue statement in your code. Get ready to go deep into the inner workings of the Python interpreter.
Inspecting Disassembled Bytecode
The Real Python bookCPython 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, authorAnthony Shaw also developed theinstaviz 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 theCPython interpreter reads, converts, and compiles your Python code. For a deeper understanding of the concepts discussed here, you’re encouraged to readCPython Internals.
It’s the disassembly of the compiled Python code as presented byinstaviz that best shows how thecontinue statement works to modify a loop. First, you’ll analyze the code below, which demonstrates how afor loop workswithoutcontinue. This example uses a modified version of the code sample you saw at the beginning of this tutorial:
code_disassembly.py 1importinstaviz 2 3defadd_numbers(): 4total=0 5 6fornumberinrange(-10,10): 7# if number < 0: 8# continue 9total+=number1011returntotal1213instaviz.show(add_numbers)The code on lines 7 and 8 iscommented out initially to analyze the loop withoutcontinue. This keeps the line numbers consistent when you compare the analysis of the initial code with the analysis that includescontinue later.
So, what’s happening here? Theinstaviz.show() function on line 13 starts aWSGIRefServer() web server onhttp://localhost:8080/, using theBottle library to format and display results in a web page. That page shows the properties of the Pythoncode object, theabstract 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 howcontinue works. A condensed and rearranged version of the code disassembly is shown below:
| 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 48 | |
| STORE_FAST | 34 | number | |
| 9 | LOAD_FAST_LOAD_FAST | 36 | (‘total’, ‘number’) |
| BINARY_OP | 38 | += | |
| STORE_FAST | 42 | total | |
| JUMP_BACKWARD | 44 | Offset 30 | |
| 10 | END_FOR | 48 | None |
| POP_TOP | 50 | None | |
| 11 | LOAD_FAST | 52 | total |
| RETURN_VALUE | 54 | None |
This reformatted table shows how thePython 3.13 interpreter analyzes the code in the listing above and turns it into internalbytecode. 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 theCPython 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 theCPython 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 theIndex Offset column and identify the relevant lines based on the numbers shown there:
- 0: Marks the start of the function definition
- 2 to 4: Initialize the
totalvariable - 6 to 34: Set up the
forloop on line 7- 6 to 20: Define and call the
rangegenerator - 28: Sets up the iterator over the defined
range - 30: Starts the iterator and defines where the loop ends at offset 48 (line 11), which is also where code execution continues when the iterator is exhausted
- 34: Sets up the
numberiterator variable
- 6 to 20: Define and call the
- 36 to 44: Modify the
totalvariable- 36: Loads the values of
totalandnumber - 38: Performs the
+=binary operation between the two values - 42: Stores the result back in
total - 44: Executes the
JUMP_BACKWARDoperation to go back to the next iteration at offset 30
- 36: Loads the values of
- 48: Continues code execution here after the
forloop has exhausted the iterator - 50: Removes any stack values remaining from the
range()generator - 52: Retrieves the value of
totalto be returned at the end of the function - 54: Returns the value of
total
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 thecontinue statement back in:
code_disassembly.py 1importinstaviz 2 3defadd_numbers(): 4total=0 5 6fornumberinrange(-10,10): 7ifnumber<0: 8continue 9total+=number1011returntotal1213instaviz.show(add_numbers)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 | None |
The 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:
- 36: Starts the
ifstatement by loading the value ofnumber. - 38: Loads the integer constant value of
0. - 40: Compares these two values using
<, the less-than operator. - 44: Transfers control to offset 52 if
number < 0isFalse, usingPOP_JUMP_IF_FALSE. - 48: Executes the
continuestatement on line 9 by transferring control to offset 30, which starts the next iteration of theforloop.
Note that there are two operations that useJUMP_BACKWARD to jump to the same place:
- Offset 48, the
continuestatement at line 8 - Offset 60, the natural end of the loop at line 9
Both operations jump to the top of thefor loop at offset 30. This shows that thecontinue 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 whycontinue doesn’t impact the execution ofelse orfinally clauses: it behaves the same as reaching the end of the loop.
Conclusion
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:
- Use
continuetomove to the next iteration of afororwhileloop, skipping the rest of the loop body for that iteration - Apply the
continuestatement toreal-world coding tasks - Avoid potential pitfalls, such as skipping necessary code and confusing
continuewith thebreakkeyword - Read disassembled CPython bytecode to understand how
continueis implemented and how it affects control flow
With this knowledge, you can now confidently and effectively usecontinue 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 Questions
Now that you have some experience using thecontinue 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 theShow/Hide toggle beside each question to reveal the answer.
You use thecontinue 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 afor loop, thecontinue 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 usecontinue in awhile 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 usecontinue in a loop with anelse clause, theelse block still runs after the loop finishes all its iterations, even if some iterations were skipped withcontinue.
A common mistake is confusingcontinue withbreak, which exits the loop entirely. Another mistake is skipping necessary code aftercontinue, 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:
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 Tricks 💌
Get a short & sweetPython Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

AboutJon Fincher
Jon taught Python and Java in two high schools in Washington State. Previously, he was a Program Manager at Microsoft.
» More about JonMasterReal-World Python Skills With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
MasterReal-World Python Skills
With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
What Do You Think?
What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.
Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students.Get tips for asking good questions andget answers to common questions in our support portal.
Looking for a real-time conversation? Visit theReal Python Community Chat or join the next“Office Hours” Live Q&A Session. Happy Pythoning!
Keep Learning
Related Learning Paths:
Related Tutorials:
Keep reading Real Python by creating a free account or signing in:
Already have an account?Sign-In





