Blog Post #39: Skipping Ahead: Using the continue Statement

In Post #38, we learned how to use the break statement to exit a loop entirely. It’s our “emergency exit” when we’ve found what we’re looking for or need to stop the whole process immediately.

But what if we don’t want to end the whole loop? What if we simply want to skip the current item we’re processing and move on to the next one? For this, Python gives us a related command: the continue statement.

In this post, you’ll learn how to use continue to bypass a single iteration of a loop without terminating the loop itself.

break vs. continue: The Key Difference

It’s crucial to understand the difference between these two keywords.

  • break: Exits the loop completely. No more iterations will run. The party is over.
  • continue: Skips the rest of the current iteration only. The loop will immediately start the next iteration. This one song is skipped, but the party continues.

How the continue Statement Works

When the Python interpreter encounters the continue keyword, it immediately stops processing the current iteration of the loop body. Any code inside the loop that comes after the continue statement is ignored for that single iteration, and the loop proceeds to its next cycle.

  • In a for loop, it moves on to the next item in the sequence.
  • In a while loop, it jumps back to the top to check the while condition again.

Using continue in a for Loop

The continue statement is very useful for “filtering” or “skipping” items inside a loop based on a condition.

Let’s write a program to print only the odd numbers from 1 to 10. We can loop through all the numbers, and if a number is even, we just continue to the next one.

print("Printing odd numbers from 1 to 10:")

for number in range(1, 11):
    # We use the modulus operator from Post #13 to check if a number is even.
    if number % 2 == 0:
        continue # If it's even, skip the rest of this iteration

    # This print statement will only be reached for odd numbers.
    print(number)

Let’s trace this. When number is 2, the if condition (2 % 2 == 0) is True. The continue statement is executed, and Python immediately skips the print(number) line and starts the next iteration where number becomes 3. This is why only the odd numbers are printed.

A More Practical Example: Processing Data

Imagine you have a list of data points to process, but some of them are invalid (e.g., negative numbers or zero). You want to process only the valid data and log a message for the invalid ones.

data_points = [10, 25, -5, 8, 0, 30, -1]

print("Processing valid data points (must be positive):")
for data in data_points:
    if data <= 0:
        print(f"Skipping invalid or zero data point: {data}")
        continue

    # This block of code only runs for valid, positive data
    print(f"Processing data point: {data}...")
    # ...imagine more complex processing code here...

The output will be:

Processing valid data points (must be positive):
Processing data point: 10...
Processing data point: 25...
Skipping invalid or zero data point: -5
Processing data point: 8...
Skipping invalid or zero data point: 0
Processing data point: 30...
Skipping invalid or zero data point: -1

The continue statement provides an elegant way to handle and filter data inside a loop without needing a complex if-else structure.

What’s Next?

continue is a powerful control flow statement that gives you fine-grained control over your loops. It allows you to selectively skip iterations based on a condition, making your code for filtering and data processing much cleaner.

We’ve now seen how to control the flow inside a loop with break and continue. But Python has one more, rather unusual, feature related to loops that often surprises even experienced programmers. What if you wanted to run a block of code only if a loop finished its course without being interrupted by a break? In Post #40, we will explore the curious case of the else block in loops.

Author

Debjeet Bhowmik

Experienced Cloud & DevOps Engineer with hands-on experience in AWS, GCP, Terraform, Ansible, ELK, Docker, Git, GitLab, Python, PowerShell, Shell, and theoretical knowledge on Azure, Kubernetes & Jenkins. In my free time, I write blogs on ckdbtech.com

Leave a Comment