Python Nested While Loop

Python While Loop is just another Python statement. As you already know that while loop body can contain statements, we can write while loop inside while loop. While loop inside another while loop is called Nested While Loop.

In this tutorial, we shall go through some of the examples, that demonstrate the working and usage of nested while loop in Python.

Syntax

Following is the quick code snippet of a while loop inside another while loop.

#statement(s)
while condition_1 :
    #statement(s)
    while condition_2 : 
        #statement(s)
ADVERTISEMENT

Example 1 – While Loop inside Another While Loop

In this example, we shall write a while loop inside another while loop.

Python Program

i = 1
while i <= 4 :
    j = 0
    while  j <= 3 :
        print(i*j, end=" ")
        j += 1
    print()
    i += 1
Try Online

Output

0 1 2 3
0 2 4 6
0 3 6 9
0 4 8 12

Example 2 – 3 Level Nested While Loop

In this example, we shall write a nested while loop inside another while loop. Like three while loops one inside another.

Python Program

i = 1
while i <= 4 :
    j = 0
    while  j <= 3 :
        k = 0
        while  k <= 5 :
            print(i*j*k, end=" ")
            k += 1
        print()
        j += 1
    print()
    i += 1
Try Online

Output

0 0 0 0 0 0
0 1 2 3 4 5
0 2 4 6 8 10
0 3 6 9 12 15

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

0 0 0 0 0 0
0 3 6 9 12 15
0 6 12 18 24 30
0 9 18 27 36 45

0 0 0 0 0 0
0 4 8 12 16 20
0 8 16 24 32 40
0 12 24 36 48 60

Conclusion

In this Python Tutorial, we learned how to write Nested While Loops in Python.