Python Nested While Loop
A nested while loop is a while loop placed inside the body of another while loop. The outer loop controls how many times the inner loop is started, and the inner loop completes its own iterations for each iteration of the outer 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)
The indentation determines which statements belong to the outer loop and which belong to the inner loop. In a typical nested while loop, both loops also need statements that eventually make their conditions false.
How a Nested While Loop Executes in Python
For each iteration of the outer while loop, Python starts the inner while loop and keeps executing it while its condition remains true. When the inner condition becomes false, execution continues with the remaining statements in the outer loop. The outer condition is then checked again.
- Check the outer loop condition.
- Enter the outer loop if its condition is true.
- Initialize or reset the variable used by the inner loop when required.
- Check the inner loop condition.
- Repeat the inner loop until its condition becomes false.
- Continue with the remaining statements in the outer loop.
- Update the outer loop variable and check its condition again.
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
Output
0 1 2 3
0 2 4 6
0 3 6 9
0 4 8 12
The outer loop runs with i values from 1 through 4. At the beginning of every outer-loop iteration, j is set to 0. The inner loop then runs with j values from 0 through 3 and prints i*j.
Resetting j inside the outer loop is important. It allows the inner loop to start again from 0 whenever the value of i changes.
Reset the Inner While Loop Variable for Each Outer Iteration
A common mistake with nested while loops is initializing the inner loop variable only once, before the outer loop. After the inner loop finishes the first time, its condition may remain false during later outer-loop iterations.
For example, the following program places j = 1 inside the outer loop so that the inner loop starts again for every row.
i = 1
while i <= 3:
j = 1
while j <= 3:
print(i, j)
j += 1
i += 1
Output
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Here, each value of i is paired with all three values of j. This row-and-column style of processing is one of the common uses of nested loops.
Python Nested While Loop for a Number Pattern
Nested while loops can be used when one repeated operation has to run inside another repeated operation. The following example prints a triangular number pattern. The outer loop controls the row, while the inner loop controls how many numbers are printed on that row.
row = 1
while row <= 4:
column = 1
while column <= row:
print(column, end=" ")
column += 1
print()
row += 1
Output
1
1 2
1 2 3
1 2 3 4
When row is 1, the inner loop executes once. When row is 4, the inner loop executes four times.
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
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
This example has three loop levels. For each value of i, the second loop goes through its values of j. For every combination of i and j, the innermost loop goes through the values of k.
Using break in a Python Nested While Loop
A break statement terminates the loop in which that break appears. Therefore, a break inside the inner while loop stops only that inner loop; it does not automatically stop the outer while loop.
i = 1
while i <= 3:
j = 1
while j <= 5:
if j == 3:
break
print(i, j)
j += 1
i += 1
Output
1 1
1 2
2 1
2 2
3 1
3 2
Whenever j becomes 3, the inner loop ends. The outer loop still proceeds to its next value of i.
Using continue in a Python Nested While Loop
A continue statement also applies to the loop in which it appears. In a while loop, make sure the loop-control variable is updated before reaching continue when necessary. Otherwise, the same condition can be evaluated repeatedly and produce an infinite loop.
i = 1
while i <= 2:
j = 0
while j < 4:
j += 1
if j == 2:
continue
print(i, j)
i += 1
Output
1 1
1 3
1 4
2 1
2 3
2 4
The iteration where j is 2 is skipped, but the inner loop continues with the next value.
Avoid Infinite Loops in Nested While Loops
Every active while-loop condition must eventually become false unless the loop is intentionally terminated with a statement such as break. With nested loops, this applies independently to both the outer and inner loops.
For example, omitting j += 1 from an inner loop whose condition is j <= 3 would cause that inner loop to repeat indefinitely. The outer loop would never reach its next iteration because Python would remain inside the inner loop.
How Many Times Does a Nested While Loop Run?
The total number of inner-loop iterations depends on the loop conditions. If an outer loop executes n times and its inner loop executes m times during every outer iteration, the inner body executes n × m times.
For example, an outer loop that runs 4 times with an inner loop that runs 3 times performs 12 inner-loop iterations. If the inner-loop limit depends on the outer-loop value, the number of iterations can vary from one outer iteration to another.
Nested While Loop vs Nested For Loop in Python
Both while and for loops can be nested. A nested while loop is useful when repetition is controlled primarily by conditions that can change while the program runs. A nested for loop is often simpler when iterating over known sequences, ranges, rows, columns, or other iterable values.
With while loops, you normally initialize and update the loop-control variables yourself. This gives explicit control over the conditions, but it also means you must ensure that every loop can terminate.
When to Use Nested While Loops in Python
A nested while loop is suitable when each repetition of one condition requires another condition-controlled repetition. Typical cases include processing rows and columns with changing limits, generating patterns, repeatedly checking combinations of values, and handling multi-level processes whose stopping conditions are not known in advance.
Deeply nested loops can become difficult to read and maintain. When several levels of nesting are required, consider whether part of the logic can be moved into a function or expressed with a clearer data-processing approach.
Python Nested While Loop Key Points
- A while loop can be placed inside another while loop in Python.
- The inner loop normally completes its iterations for each iteration of the outer loop.
- Reset the inner loop variable inside the outer loop when the inner loop must start from its initial value again.
- Update the control variables so that both loop conditions can eventually become false.
- A
breakorcontinueinside the inner loop affects that inner loop, not every enclosing loop automatically. - More than two levels of while-loop nesting are possible, but excessive nesting can make code harder to understand.
Conclusion
In this Python Tutorial, we learned how to write Nested While Loops in Python.
TutorialKart.com