Introduction
The Python continue
statement allows you to skip the rest of the current iteration and resume executing the code from the next one. It is conceptually very similar to the break
statement, which exits the loop entirely. While the break
statement is used to exit a loop, the continue
statement will just skip the rest of the current iteration and pick up with the following one. Like break
, continue
can be used with both for
and while
loops.
Basic continue Statement Syntax
To skip the rest of the code in an iteration of a loop, just write the keyword continue
on its own line. To skip the rest of the code in an iteration of a loop, just write the keyword continue
on its own line. It must be placed within a loop, otherwise a `continue` will cause a syntax error.
continue
should be used with a conditional statement since not doing so will result in useless, unreachable code following it.
Here’s the basic syntax for the continue
statement with a for
loop:
for element in iterable: # code above if condition: continue # code below
And here’s the basic syntax for continue
with a while
loop:
while loop_condition: # code above if condition: continue # code below
Using continue with for Loops
for
loops iterate through all items in an iterable, and the continue
statement is useful when you want to skip executing some code for certain items based on a condition.
Example:
dogs = ["Scooby-Doo", "Snoopy", "Goofy", "Clifford", "Astro"] sick_dogs = ["Snoopy", "Clifford"] for dog in dogs: print(f"{dog}'s activities: ") print(f" Gets a treat.") if dog in sick_dogs: continue print(f" Plays fetch.") print(f" Goes running in the yard.")
Output:
Scooby-Doo's activities: Gets a treat. Plays fetch. Goes running in the yard. Snoopy's activities: Gets a treat. Goofy's activities: Gets a treat. Plays fetch. Goes running in the yard. Clifford's activities: Gets a treat. Astro's activities: Gets a treat. Plays fetch. Goes running in the yard.
The purpose of the code in the example above is to list a day’s activities for some dogs. Every dog gets a treat, but dogs that are sick and who need rest, skip the physical activities of playing fetch and running in the yard.
It works by iterating though the dogs
array with the for
loop on line 4. The sick dogs are given by the sick_dogs
array (Snoopy and Clifford), and lines 8 and 9 skip the physical activities for those using a continue
statement.
Using continue With while Loops
The continue
statement can also be used from within while loops. Here is the example above, re-written with a while loop:
Example:
dogs = ["Scooby-Doo", "Snoopy", "Goofy", "Clifford", "Astro"] sick_dogs = ["Snoopy", "Clifford"] i = 0 while i < len(dogs): dog = dogs[i] i += 1 print(f"{dog}'s activities: ") print(f" Gets a treat.") if dog in sick_dogs: continue print(f" Plays fetch.") print(f" Goes running in the yard.")
Output:
Scooby-Doo's activities: Gets a treat. Plays fetch. Goes running in the yard. Snoopy's activities: Gets a treat. Goofy's activities: Gets a treat. Plays fetch. Goes running in the yard. Clifford's activities: Gets a treat. Astro's activities: Gets a treat. Plays fetch. Goes running in the yard.
The example above is the same as the prior example, except that it uses a while
loop. By using a while loop, we have to add some indexing code that the for
loop does for us behind the scenes.
The program initializes the index i
on line 4, and then accesses a dog item from the array on line 6. The value of the index is incremented on line 7 in order to fetch the next dog on the next iteration. In this case, we must be sure to increment i
before the continue block on lines 12 and 13. Otherwise, it won’t be incremented for the first sick dog, and the program will get stuck in an infinite loop.
Understanding Python continue Behavior in Nested Loops
Similar to the break
statement, the continue
statement only affects the innermost loop where it is located when used within nested loops.
Example:
for i in range(3): for j in range(3): if j == i: continue print(f"({i}, {j})")
Output:
(0, 1) (0, 2) (1, 0) (1, 2) (2, 0) (2, 1)
The above example prints all pairs of integers from 0 to 2, but skips the ones that have two of the same number. It does this by using two nested for
loops on lines 1 and 2. It then tests whether the numbers are equal on line 3, and if so, skips the print statement (line 5) with the continue
on line 4. The continue
only exits the iteration of the innermost loop (the for
on line 2).
Using an if Statement as an Alternative to continue
An alternative to the continue
statement involves employing an if
statement to achieve similar code execution logic. By strategically placing the if
statement within the loop structure, specific code blocks can be conditionally executed or skipped based on the desired criteria.
This alternative approach enhances code readability, making it easier to identify conditions influencing the execution of specific code segments. The decision between using an if
statement or the continue
statement often comes down to personal stylistic preferences, with both options offering effective ways to control loop flow.
Example:
dogs = ["Scooby-Doo", "Snoopy", "Goofy", "Clifford", "Astro"] sick_dogs = ["Snoopy", "Clifford"] for dog in dogs: print(f"{dog}'s activities: ") print(f" Gets a treat.") if dog not in sick_dogs: print(f" Plays fetch.") print(f" Goes running in the yard.")
The example above performs the same logic as the first example and results in the same output. However, instead of using a continue
to skip physical activities for the sick dogs, it uses the if
statement on line 8.
The if dog in sick_dogs:
conditional (line 8) in the original code becomes if dog not in sick_dogs:
with the addition of the not
operator. The original code skipped physical activity if a dog is sick, whereas now this code permits the physical activity (performed by the indented code on lines 9 and 10) if the dog is not sick.
Summary & Reference for the Python continue Statement
The Python continue
statement provides a way to skip the rest of the current iteration within loops, allowing the code to resume with the next iteration. Similar to the break
statement, continue
is often employed within conditional statements to selectively execute code based on specific conditions.
To apply the continue
statement, place it on its own line within a loop, typically within an if
statement that checks a particular condition.
Here is an example of using continue
from within a for
loop:
for dog in dogs: # Some code if dog in sick_dogs: continue # Code for activities of non-sick dogs
Here is an example of using continue
from within a while
loop:
i = 0 while i < len(dogs): # Some code if dogs[i] in sick_dogs: i += 1 continue # Code for activities of non-sick dogs
An if
statement can be used as an alternative to continue
to allow the same execution logic and enhance readability.
When used within nested loops, the continue
statement affects only the innermost loop where it is located.