Example 7: Confusing inner and outer loops

A common challenge is understanding the correct interaction between the inner and outer loops. Instead of trying to immediately understand what both loops are doing, tell your students to focus on one loop at a time. They need to understand the inner loop for a fixed value of the outer loop.

We want to print a table consisting of three rows and six columns:

1 2 3 4 5 6
1 2 3 4 5 6
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, as shown below in the left code.

# 03Loops example_07_inner_outer loops-1.py
# prints three rows, each having six integers  

for i in range (1,4): 		# i controls the number of rows
    for j in range (1,7): 	# j controls the number of columns
        print(j),
    print     # Add a new line
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
# 03Loops example_07_inner_outer loops-2.py
# prints six rows, each having three integers  

for i in range (1,7):
    for j in range (1,4):
        print(j),
    print
1 2 3
1 2 3
1 2 3
1 2 3
1 2 3
1 2 3

Swapping the order of outer and inner loop (as shown in the code on the right side) produces six rows and three columns.