Python While Loop with Continue Statement

Python While Loop executes a set of statements in a loop based on a condition. But, in addition to the standard execution of statements in a loop, you can skip the execution of statement(s) in while loop for this iteration, using builtin Python continue statement.

If there are nested looping statement, continue statement applies only for the immediate enclosing while loop.

In this tutorial, we will learn how to skip the execution of subsequent statements in a while loop and continue with the further iterations, using continue statement.

Syntax

Following is the syntax of while loop with a break statement in it.

#statement(s)
while condition :
    #statement(s)
    if continue_condition :
        continue
    #statement(s)

Following is the flow-diagram of while loop with continue statement.

When the continue condition is true, continue statement executes and continues with the next iteration of the loop.

Also, please note that the placement of continue statement inside while loop is up to you. You can have statements before and after the continue statement in while loop body.

Example Python While Loop Continue

In this example, we shall write a Python program with while loop to print numbers from 1 to 20. But, when we get an odd number, we will continue the loop with next iterations.

Python Program

i = 0
while i <= 20 :
    i += 1
    if i % 2 == 1 :
        continue
    print(i)

Make sure that you update the control variables participating in the while loop condition, before you execute the continue statement.

Output

2
4
6
8
10
12
14
16
18
20

Example Continue in Nested While Loop

In this example, we shall write a Python program with an nested while loop. We will use continue statement in the body of inner while loop based on some condition.

Python Program

i = 1
while i < 6 :
    j = 1
    while j < 8 :
        if j % 2 == 1 :
            j += 1
            continue
        print(i*j, end=" ")
        j += 1
    print()
    i += 1

Output

2 4 6
4 8 12
6 12 18
8 16 24
10 20 30

Conclusion

In this Python Tutorial, we learned how to use continue statement in Python While Loop.