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:

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

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

Detailed Explanation:

The continue statement is a powerful tool for optimizing loop control by allowing selective skipping of iterations while maintaining the loop flow.