Skip to content

Nested while loop Python | Example code

  • by

If you are using a while loop inside another while loop then it is called a nested while loop in Python. The syntax for nesting while loop in Python is:

while (expression_1):  # Outer loop
    [code to execute]  # Optional
while (expression_2):  # Inner loop
    [code to execute]

Example Nested while loop in Python

Simple example code While loop will keep on executing the code until the expression evaluates to true. Don’t forget to update the iterating variable/expression otherwise, it enters infinite execution mode.

i = 1
j = 5

while i < 4:

    while j < 8:

        print(i, ",", j)

        j = j + 1
        i = i + 1

Output:

Nested while loop Python

Level Nested While Loop

i = 1
while i <= 2:
    j = 0
    while j <= 2:
        k = 0
        while k <= 2:
            print(i * j * k, end=" ")
            k += 1
        print()
        j += 1
    print()
    i += 1

Output:

0 0 0 
0 1 2 
0 2 4 

0 0 0 
0 2 4 
0 4 8 

How does a nested while loop work?

Answer: Nested while the loop works one iteration of the outer loop first executes, after which the inner loop executes. When the condition of the inner loop gets satisfied, the program moves to the next iteration of the outer loop.

Please comment if you have any doubts or suggestions on this Python Nested loop code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading