Continue Statement in Python
The continue statement in Python is used to skip the current iteration of a loop and move directly to the next iteration. It’s helpful for skipping certain values within a loop without breaking out of the loop entirely.
Key Points on Continue Statement:
- The continue statement is generally used to skip specific iterations within
for
orwhile
loops based on a condition. - When
continue
is executed, the loop doesn’t terminate but instead proceeds to the next iteration. - It is useful for avoiding specific values in a loop, such as skipping odd or even numbers.
- The continue statement only affects the current loop iteration, making it ideal for selectively bypassing iterations without stopping the entire loop.
Example of Using Continue in a Loop:
In this example, the for
loop skips the number 5 and continues with the remaining numbers.
Code Example
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for num in numbers:
if num == 5:
continue
print(num)
Output
1
2
3
4
6
7
8
9
2
3
4
6
7
8
9
Continue in Nested Loops:
This example demonstrates using continue
within a nested loop. The inner loop skips even numbers while printing the values of the odd numbers.
Code Example 2
for i in range(1, 4):
for j in range(1, 6):
if j % 2 == 0:
continue
print(f"i={i}, j={j}")
Output
i=1, j=1
i=1, j=3
i=1, j=5
i=2, j=1
i=2, j=3
i=2, j=5
i=3, j=1
i=3, j=3
i=3, j=5
i=1, j=3
i=1, j=5
i=2, j=1
i=2, j=3
i=2, j=5
i=3, j=1
i=3, j=3
i=3, j=5
Detailed Explanation:
- Condition Check: The
continue
statement executes only if the specified condition in the loop is met. - Inner Loop Execution: In nested loops,
continue
will only skip the iteration in the innermost loop where it’s placed, without affecting outer loops. - Efficiency:
continue
can be used to skip processing unnecessary values within loops, improving loop efficiency for selective processing. - Alternatives: Without
continue
, you would need additional conditional checks, potentially making the code more complex.
The continue statement is a powerful tool for optimizing loop control by allowing selective skipping of iterations while maintaining the loop flow.