Skip to content

Informatics Practices · Ch 3 — Brief Overview of Python

Nested Loops

3.13

Nested Loops

A loop may itself contain another loop inside its body. A loop written inside another loop is called a nested loop. The loop that encloses is the outer loop; the loop sitting inside it is the inner (nested) loop.

The rule that governs how a nested loop runs is simple but crucial: for every single iteration of the outer loop, the inner loop runs through all of its iterations from the beginning. The two loops do not advance together — the outer loop takes one step, then waits while the inner loop completes its entire cycle, then takes its next step, and so on.

Program 3-6 demonstrates the working of nested for loops:

#Program 3-6
#Demonstrate working of nested for loops
for var1 in range(3):
    print("Iteration " + str(var1 + 1) + " of outer loop")
    for var2 in range(2):        #nested loop
        print(var2 + 1)
    print("Out of inner loop")
print("Out of outer loop")

Output:

Iteration 1 of outer loop
1
2
Out of inner loop
Iteration 2 of outer loop
1
2
Out of inner loop
Iteration 3 of outer loop
1
2
Out of inner loop
Out of outer loop

Trace the execution line by line to see the pattern:

  • The outer loop's range(3) gives var1 the values 0, 1 and 2, so the outer body runs three times.
  • On each outer pass, the program first announces the pass number. Since var1 starts from 0 but humans count from 1, the code prints var1 + 1. The value must be converted with str() before it can be joined to the surrounding text with +, because + concatenates only strings with strings — that is why the statement reads "Iteration " + str(var1 + 1) + " of outer loop".
  • Control then enters the inner loop. Its range(2) gives var2 the values 0 and 1, and the body prints var2 + 1, producing the lines 1 and 2. The inner loop runs to completion — both iterations — before anything else happens.
  • Only after the inner loop is exhausted does the statement print("Out of inner loop") execute. It is indented at the level of the outer loop's body, so it belongs to the outer loop and runs once per outer pass — three times in total.
  • Finally, print("Out of outer loop") is not indented under any loop at all, so it runs exactly once, after the outer loop has finished all three of its passes.

Counting the work makes the structure vivid: the outer body runs 3 times, and since the inner loop performs 2 iterations on each of those passes, the inner body runs 3 × 2 = 6 times in total — which is why the digits 1 and 2 appear three times over in the output.

Important

Indentation decides which loop owns a statement. print(var2 + 1) is indented inside the inner loop, so it runs six times; print("Out of inner loop") is indented only inside the outer loop, so it runs three times; print("Out of outer loop") stands outside both, so it runs once. …