Movatterモバイル変換


[0]ホーム

URL:


— FREE Email Series —

🐍 Python Tricks 💌

Python Tricks Dictionary Merge

🔒 No spam. Unsubscribe any time.

Browse TopicsGuided Learning Paths
Basics Intermediate Advanced
aialgorithmsapibest-practicescareercommunitydatabasesdata-sciencedata-structuresdata-vizdevopsdjangodockereditorsflaskfront-endgamedevguimachine-learningnewsnumpyprojectspythonstdlibtestingtoolsweb-devweb-scraping

Table of Contents

Skip Ahead in Loops With Python's Continue Keyword

Skip Ahead in Loops With Python's continue Keyword

byJon FincherPublication date Aug 04, 2025Reading time estimate 28mbasicspython

Table of Contents

Remove ads

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:

  • Executingcontinuedoesn’t affect theelse clause of a loop.
  • Usingcontinue incorrectly may result inskipping necessary code.
  • You can’t usecontinue in a function or class that’s nested in a loop.
  • On abytecode 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 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:


Skip Ahead in Loops With Python's Continue Keyword

Interactive Quiz

Skip Ahead in Loops With Python's continue Keyword

Test 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:

  • Afor loop runs a specific number of times and is usually used to process a collection of data.
  • Awhile 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 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:

Python
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:

Python
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:

Pythonsum_whole_numbers.py
print("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:

Pythonsum_whole_numbers.py
print("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:

Shell
$pythonsum_whole_numbers.pyEnter one whole number per input.Type 0 to stop and display their sum:+ 1+ 2+ -100+ 0total=3

The 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:

Python
 1fornumberinrange(1,10): 2ifnumber%2==1: 3continue 4 5print(number**2) 6 7else: 8print("Done")

This results in the following output:

Program Output
4163664Done

The 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:

Python
 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:

Program Output
4163664Done

In 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:

Pythonaoc_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:

Python
 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:

Python
 1number=1 2 3whilenumber<=10: 4ifnumber%2==1: 5continue 6 7print(number**2) 8number+=1

This 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:

Python
 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:

Python
 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:

Python
 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:

Python
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:

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:

Python
 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 loop

Thecontinue 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:

Python
 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...111123135147159

This 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:

Python
 1>>>defcheck_even(number): 2...returnnumber%2==0 3... 4>>>fornumberinrange(10): 5...ifcheck_even(number): 6...continue 7...else: 8...print(number) 9...101113125137149

Later in the same documentation, you’ll find the following passage:

Whencontinue passes control out of atry statement with afinally clause, thatfinally clause 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:

Pythoncontinue_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, whennumber 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, whennumber == 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.

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:

Pythoncode_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 NumberOperation NameIndex OffsetResolved Arg Value
3RESUME00
4LOAD_CONST20
STORE_FAST4total
6LOAD_GLOBAL6range
LOAD_CONST16-10
LOAD_CONST1810
CALL202
GET_ITER28None
FOR_ITER30Offset 48
STORE_FAST34number
9LOAD_FAST_LOAD_FAST36(‘total’, ‘number’)
BINARY_OP38+=
STORE_FAST42total
JUMP_BACKWARD44Offset 30
10END_FOR48None
POP_TOP50None
11LOAD_FAST52total
RETURN_VALUE54None

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 thetotal variable
  • 6 to 34: Set up thefor loop on line 7
    • 6 to 20: Define and call therange generator
    • 28: Sets up the iterator over the definedrange
    • 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 thenumber iterator variable
  • 36 to 44: Modify thetotal variable
    • 36: Loads the values oftotal andnumber
    • 38: Performs the+= binary operation between the two values
    • 42: Stores the result back intotal
    • 44: Executes theJUMP_BACKWARD operation to go back to the next iteration at offset 30
  • 48: Continues code execution here after thefor loop has exhausted the iterator
  • 50: Removes any stack values remaining from therange() generator
  • 52: Retrieves the value oftotal to be returned at the end of the function
  • 54: Returns the value oftotal

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:

Pythoncode_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 NumberOperation NameIndex OffsetResolved Arg Value
3RESUME00
4LOAD_CONST20
STORE_FAST4total
6LOAD_GLOBAL6range
LOAD_CONST16-10
LOAD_CONST1810
CALL202
GET_ITER28None
FOR_ITER30Offset 64
STORE_FAST34number
7LOAD_FAST36number
LOAD_CONST380
COMPARE_OP40<
POP_JUMP_IF_FALSE4452
8JUMP_BACKWARD48Offset 30
9LOAD_FAST_LOAD_FAST52(‘total’, ‘number’)
BINARY_OP5413
STORE_FAST58total
JUMP_BACKWARD60Offset 30
10END_FOR64None
POP_TOP66None
11LOAD_FAST68total
RETURN_VALUE70None

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 theif statement by loading the value ofnumber.
  • 38: Loads the integer constant value of0.
  • 40: Compares these two values using<, the less-than operator.
  • 44: Transfers control to offset 52 ifnumber < 0 isFalse, usingPOP_JUMP_IF_FALSE.
  • 48: Executes thecontinue statement on line 9 by transferring control to offset 30, which starts the next iteration of thefor loop.

Note that there are two operations that useJUMP_BACKWARD to jump to the same place:

  1. Offset 48, thecontinue statement at line 8
  2. 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:

  • Usecontinue tomove to the next iteration of afor orwhile loop, skipping the rest of the loop body for that iteration
  • Apply thecontinue statement toreal-world coding tasks
  • Avoid potential pitfalls, such as skipping necessary code and confusingcontinue with thebreak keyword
  • Read disassembled CPython bytecode to understand howcontinue is 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:


Skip Ahead in Loops With Python's Continue Keyword

Interactive Quiz

Skip Ahead in Loops With Python's continue Keyword

Test 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.

Python Tricks Dictionary Merge

AboutJon Fincher

Jon taught Python and Java in two high schools in Washington State. Previously, he was a Program Manager at Microsoft.

» More about Jon

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

MasterReal-World Python Skills With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

MasterReal-World Python Skills
With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

What Do You Think?

Rate this article:

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 Topics:basicspython

Related Learning Paths:

Related Tutorials:

Keep reading Real Python by creating a free account or signing in:

Already have an account?Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Skip Ahead in Loops With Python's Continue Keyword

Skip Ahead in Loops With Python's Continue Keyword (Sample Code)

🔒 No spam. We take your privacy seriously.


[8]ページ先頭

©2009-2026 Movatter.jp