Nested Loops
A loop can contain another loop. This is called a nested loop. In each iteration of the outer loop, the inner loop runs all the way through. Let's list every T-shirt a shop sells, in every size and every color:
sizes = ["S", "M"]
colors = ["red", "blue", "black"]
for size in sizes:
for color in colors:
print(size, color)This prints:
S red
S blue
S black
M red
M blue
M blackThe outer loop takes "S", and the inner loop goes through all three colors. Only then does the outer loop take "M", and the inner loop goes through all the colors again. The inner block runs 2 × 3 = 6 times. The inner loop is indented inside the outer one, and its own block is indented once more. Give the variables of the two loops different names (here size and color), so that you know which is which.
Nested loops are also handy for printing tables. So far, every print() has ended its line. With end=" ", it ends with a space instead, and the next print() continues on the same line. An empty print() then ends the line. This prints part of a multiplication table, one row for each number:
for row in range(1, 4):
for column in range(1, 6):
print(row * column, end=" ")
print()1 2 3 4 5
2 4 6 8 10
3 6 9 12 15 Look at where the empty print() is: it is indented only once, so it belongs to the outer loop. It runs each time the inner loop has printed a whole row.
Instructions
A travel agency offers a trip to each city in cities with each activity in activities. Write a loop over cities and, nested inside it, a loop over activities, and print every pair with print(city, activity). The output starts with Prague Tennis, Prague Shopping, Prague Sightseeing, Paris Tennis…
Below that, print a small multiplication table from 1 to 5: five rows with five numbers each, separated by spaces. The first row is 1 2 3 4 5, the second one 2 4 6 8 10 and the last one 5 10 15 20 25. Use two nested loops with range(), print(..., end=" ") and an empty print().