How to use the `continue` statement in a `while` loop in Python

Published on Aug. 22, 2023, 12:16 p.m.

To use the continue statement in a while loop in Python, you can add an if statement within the loop to check for a certain condition. If the condition is met, you can use the continue statement to skip the current iteration and continue to the next iteration of the loop. Here is an example:

i = 0
while i < 10:
    i += 1
    if i == 5:
        continue
    print(i)

In this example, the while loop iterates through the numbers 1 to 10. If the current value of i is equal to 5, the continue statement is executed, which skips the current iteration of the loop and continues to the next iteration. This means that the number 5 will be skipped in the output.

The output of this program will be:

1
2
3
4
6
7
8
9
10

Note that the continue statement can be used in any type of loop in Python, including for loops and nested loops.

Tags: