Computer Science · Ch 6 — Flow of Control
Nested Loops
Nested Loops
A loop may contain another loop inside its body. A loop placed inside another loop is called a nested loop. For every single iteration of the outer loop, the inner loop runs through all of its own iterations from the start.
Python imposes no restriction on how many loops can be nested inside a loop, or on the number of levels of nesting. Moreover, any type of loop may be nested within any other — a for inside a for, a while inside a for, a for inside a while, or a while inside a while.
A for loop nested inside a for loop
# Working of nested for loops
for outer in range(3):
print("Iteration " + str(outer + 1) + " of outer loop")
for inner in range(2): # nested loop
print(inner + 1)
print("Out of inner loop")
print("Out of outer loop")
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
The outer loop runs 3 times; on each of those passes the inner loop runs its full 2 iterations, so the inner body executes 6 times in all. Notice how the messages trace the flow: entering an outer iteration, completing the whole inner loop, then moving to the next outer iteration.
Printing a number pattern
Nested loops are the standard tool for row-and-column output: the outer loop produces the rows, the inner loop produces the entries within a row. To print, for a user-input number, the pattern
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
each row i must contain the numbers 1 to i on one line:
# Print the triangular pattern for a number input by the user
limit = int(input("Enter a number to generate its pattern = "))
for row in range(1, limit + 1):
for col in range(1, row + 1):
print(col, end=" ") # stay on the same line
print() # move to the next line after each row
Enter a number to generate its pattern = 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
The end=" " keeps the inner loop's values on one line, and the bare print() after the inner loop starts a fresh line for the next row.
A while loop nested inside a for loop — primes from 2 to 50
Any loop type can sit inside any other. Here a while loop searches for a factor of each candidate i supplied by the outer for loop; break leaves the inner loop as soon as a factor is found, and a candidate with no factor up to half its value is prime:
# Find the prime numbers between 2 and 50 using nested loops
for i in range(2, 50):
j = 2
while j <= (i / 2):
if i % j == 0: # factor found
break # break out of the while loop
j += 1
if j > i / 2: # no factor found up to i/2
print(i, "is a prime number")
print("Bye Bye!!")
2 is a prime number
3 is a prime number
5 is a prime number
7 is a prime number
11 is a prime number
13 is a prime number
17 is a prime number
19 is a prime number
23 is a prime number
29 is a prime number
31 is a prime number
37 is a prime number
41 is a prime number
43 is a prime number
47 is a prime number
Bye Bye!!
Note that break here exits only the inner while loop — the outer for loop carries on with the next candidate. After the inner loop ends, the value of j tells the story: if it climbed past i / 2, no factor was ever found.