Python continue Statement: Skip Iterations Efficiently

Master the Python `continue` statement to skip current loop iterations & efficiently process data, ideal for filtering in AI/ML workflows.

2.5 Python continue Statement

The continue statement in Python is a powerful control-flow tool used within loops (for and while). Its primary purpose is to skip the remaining code within the current iteration of the loop and immediately proceed to the next iteration.

When to Use continue

The continue statement is particularly useful in the following scenarios:

  • Filtering unwanted values: When you want to process a collection of items but ignore specific ones based on certain criteria.
  • Bypassing certain conditions: To avoid executing a block of code for particular iterations without stopping the entire loop.
  • Conditional execution within loops: When you want the loop to continue running but skip specific cases or branches of logic.

Syntax of continue

The continue statement is typically placed inside an if block within a loop:

for item in iterable:
    if condition_to_skip:
        continue  # Skips the rest of the code in this iteration
    # Code to execute if the condition is NOT met
    # ...

while condition:
    if condition_to_skip:
        continue  # Skips the rest of the code in this iteration
    # Code to execute if the condition is NOT met
    # ...
    # Ensure loop variables are updated to avoid infinite loops

Using continue in a for Loop

Let's illustrate how continue works in a for loop.

Example 1: Skipping a Specific Character

This example prints each character of the string "Python", except for the letter 'h'.

print("--- Example 1: Skipping 'h' in a string ---")
for char in "Python":
    if char == "h":
        continue  # Skip this iteration if the character is 'h'
    print("Current character:", char)
print("Loop completed.")

Output:

--- Example 1: Skipping 'h' in a string ---
Current character: P
Current character: y
Current character: t
Current character: o
Current character: n
Loop completed.

As you can see, the character 'h' was skipped, and the loop continued with the next character.

Using continue in a while Loop

The continue statement functions identically within while loops.

Example 2: Finding Prime Factors

This example demonstrates finding the prime factors of a number. If the current factor divides number, it's printed, number is updated, and continue is used to re-check the same factor against the new number. This is crucial for handling repeated prime factors.

print("\n--- Example 2: Finding Prime Factors ---")
number = 60
print("Prime factors of:", number)
factor = 2

while number > 1:
    if number % factor == 0:
        print(factor)
        number = number // factor
        continue  # Check the same factor again with the reduced number
    factor += 1

print("Loop completed.")

Output:

--- Example 2: Finding Prime Factors ---
Prime factors of: 60
2
2
3
5
Loop completed.

Try It Yourself: Replace number = 60 with number = 75 and rerun the code.

Output for number = 75:

--- Example 2: Finding Prime Factors ---
Prime factors of: 75
3
5
5
Loop completed.

continue vs. break in Python

It's important to distinguish continue from break.

Featurecontinuebreak
BehaviorSkips the current iteration only.Exits the entire loop immediately.
Control FlowReturns to the loop condition check.Jumps to the code immediately after the loop.
Use CaseIgnore specific cases, process the rest.Stop the loop based on a specific condition.

Tips for Using continue Effectively

  • Prevent Infinite Loops: Always ensure your loop has a clear exit condition. If continue is used incorrectly, especially in while loops where the condition to advance the loop is skipped, you can create an infinite loop.
  • Readability: While continue can be useful, overuse can sometimes make code harder to follow. Consider if restructuring the logic or using else blocks might be clearer.
  • Targeted Skipping: continue is best when you want to skip specific, isolated cases within a larger loop process, rather than skipping the entire purpose of the loop.

The continue statement is a valuable tool for creating more flexible and efficient loops by allowing you to selectively skip iterations without prematurely terminating the loop.