Understanding the Python continue Statement in Loops
Using continue in for Loops
The continue statement skips the remaining code in the current iteration and jumps directly to the next one. In a for loop, this means moving to the next element immediately.
Printing only multiples of 3 from a range:
for num in range(1, 21):
if num % 3 != 0:
continue
print(num)
When num is not divisible by 3, the continue statement triggers, bypassing the print call. Only numbers that pass the divisibility check get printed.
Using continue in while Loops
The same mechanism works inside while loops. Here's an example that displays only odd numbers between 1 and 15:
counter = 1
while counter <= 15:
if counter % 2 == 0:
counter += 1
continue
print(counter)
counter += 1
Each time counter holds an even value, we increment it and skip the rest of the loop body. Odd values get printed before the increment happens.
continue in Nested Loops
When continue appears in nested loops, it only affects the innermost loop containing it. Consider this pattern:
for row in range(1, 4):
for col in range(1, 4):
if col == 2:
continue
print(f"Row {row}, Column {col}")
Here, when col equals 2, the inner loop advances to the next column while the outer loop continues unaffected. The output skips pairs where the column is 2.
Key Behaviors and Pitfalls
It does not exit the loop — continue only halts the current cycle. Use break when you need to terminate the entire loop early.
Scope is limited to the immediate loop — In deeply nested structures, a continue at an inner level leaves outer loops untouched. If you need to skip outer iteratiosn, restructuring the loop logic or using flag variables becomes necessary.
Prefer clarity over cleverness — Overusing continue can obscure program flow. Sometimes rearranging conditions or filtering collections produces cleaner code than stacking multiple continue statements. For instance, a list comprehension or a conditional check before entering the loop body often reads better than embedded continue blocks.
Interaction with other control flow — Combining continue with break, return, or exception handling requires careful testing. The order of these statements matters significantly and can introduec subtle bugs if not examined thoroughly.
# Example demonstrating scope limitation
for x in range(3):
for y in range(3):
if x == 1:
continue # Only skips inner loop when x equals 1
print(x, y)
The outer loop proceeds regardless of how many times the inner loop hits continue.