Skip to content

Nested while loop in Python | Example code

  • by

When a while loop is used inside another while loop then it is called nested while loop in Python. Python allows using one loop inside another loop.

while expression:             
         while expression:    
                 statement(s) 
statement(s)

Example Nested while loop in Python

Simple example code.

i = 1
j = 5
while i < 4:
    while j < 8:
        print(i, ",", j)
        j = j + 1
        i = i + 1

Output:

Nested while loop in Python

Another example

Display multiplication table using nested while in Python language.

i = 1
while i <= 5:
    j = 1
    while j <= 5:
        print(i, "*", j, '=', i * j)
        j += 1
    i += 1
    print("\n")

Output:

1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
1 * 5 = 5


2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10


3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
3 * 5 = 15


4 * 1 = 4
4 * 2 = 8
4 * 3 = 12
4 * 4 = 16
4 * 5 = 20


5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25

Do comment if you have any doubts and suggestions on this Python While loop program.

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

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.