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)
The syntax for a nested while loop in Python is as follows:
outer_condition = True
while outer_condition:
# Outer loop statements
inner_condition = True
while inner_condition:
# Inner loop statements
# Inner loop termination condition
if some_condition:
inner_condition = False
# Outer loop termination condition
if some_condition:
outer_condition = False
- Start by defining the outer condition, which determines whether the outer loop will continue executing. This condition is checked at the beginning of each iteration of the outer loop.
- Begin the outer while loop, using the
while
keyword followed by the outer condition. - Within the body of the outer loop, you can include any desired statements or instructions.
- Define the inner condition, which determines whether the inner loop will continue executing. This condition is checked at the beginning of each iteration of the inner loop.
- Start the inner while loop using the
while
keyword followed by the inner condition. - Inside the body of the inner loop, you can include the statements or instructions specific to the inner loop.
- If there is a specific condition that should terminate the inner loop before it has completed all iterations, you can include an
if
statement within the inner loop to check that condition and set theinner_condition
toFalse
if the condition is met. - If there is a specific condition that should terminate the outer loop before it has completed all iterations, you can include an
if
statement after the inner loop to check that condition and set theouter_condition
toFalse
if the condition is met. - The program will continue execution until either the inner condition or the outer condition evaluates to
False
, terminating the respective loop.
Remember to modify the code according to your specific requirements and conditions.
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:
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
Comment if you have any doubts or 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.