Nested loops are an essential part of coding. Just as one loop avoids having to write the same code over and over again, a nested loop avoids having to write a single loop over and over again. Nested loop are an abstraction needed in programming. They can be harder to follow and can at times be mind-warping.
A common challenge is to understand the correct interaction between the inner and outer loops. Instead of trying to immediately understand what both loops are doing, focus on one loop at a time. Make sure to understand the inner loop for a fixed value of the outer loop.
Example: Print a table with three rows, each containing the numbers 1 2 3 4 5 6
The correct approach is to have an outer loop be responsible for printing the three rows. An inner loop is responsible for printing the six elements in each row.
for i in range (1,4): # controls the number of rows for j in range (1,7): #controls the number of columns print(j)
1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6
Swapping the order of outer and inner loop produces:
for i in range (1,7): for j in range (1,4): print(j)
1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3
Let students experiment with making changes to the loop structure. It will help them get the experience needed to write correctly nested loops. The following two videos on nested loops demonstrate these and other challenges and uses of nested loops.
Video 1 (Video Length: 2:59)
Video 2 (Video Length: 4:33)