Python Continue Statement: Bypassing Loop Iterations Elegantly

The continue statement is a loop control keyword that immediately skips the remaining lines in the current iteration of a for or while loop. Unlike break (which kills the loop completely), continue simply jumps directly to the next iteration pass.


1. Basic Continue Example: Filtering Odd Numbers

# Print only even numbers between 1 and 10:
for num in range(1, 11):
    if num % 2 != 0:
        continue  # Skip odd numbers!
    print("Even Number:", num)

Output:

Even Number: 2
Even Number: 4
Even Number: 6
Even Number: 8
Even Number: 10

2. Real-World Use Case: Skipping Corrupt Data Records

transactions = [1200.0, -50.0, None, 450.0, "INVALID", 3200.0]

valid_total = 0.0
for tx in transactions:
    # Skip any invalid or negative data
    if not isinstance(tx, (int, float)) or tx <= 0:
        print(f"Skipping corrupt transaction entry: {tx}")
        continue

    valid_total += tx

print(f"Total Valid Processed Amount: ₹{valid_total}")

Frequently Asked Questions (FAQ)

Does continue reset the while loop condition counter?

No. Be careful when using continue inside a while loop! If you place continue before incrementing the loop variable (e.g. i += 1), you will create an accidental infinite loop.
Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!