19. Nested loops — Homework solutions
The .py solution files are in
exercises/19/homework/solutions/.
Problem 1 — Rectangle of hashes
Problem. A 5-wide, 3-tall block of
#.
How to think about it. Outer loop = rows (3). Inner
loop = columns (5): build a row of five #, then print
it.
Worked solution.
for row in range(1, 4):
line = ""
for col in range(1, 6):
line = line + "#"
print(line)Problem 2 — Coordinate pairs
Problem. Print every (x, y) for x and y
from 1 to 3.
Worked solution.
for x in range(1, 4):
for y in range(1, 4):
print(f"({x}, {y})")Output: (1, 1), (1, 2),
(1, 3), (2, 1), ... — nine lines.
Common mistakes.
- Reusing
xfor both loops. Each loop needs its own variable.
Problem 3 — Times table
Problem. A 5×5 multiplication grid.
Worked solution.
for row in range(1, 6):
line = ""
for col in range(1, 6):
line = line + str(row * col) + "\t"
print(line)Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Challenge — Right triangle
Problem. A 6-row triangle where row n
has n stars, then upside down.
Worked solution.
# growing
for row in range(1, 7):
line = ""
for star in range(1, row + 1):
line = line + "*"
print(line)
# shrinking
for row in range(6, 0, -1):
line = ""
for star in range(1, row + 1):
line = line + "*"
print(line)The two differ only in the outer loop's direction:
range(1, 7) up, range(6, 0, -1) down. The
inner loop is identical.
Common mistakes.
- Using a fixed inner range
range(1, 7)instead ofrange(1, row + 1). A fixed inner range gives a rectangle; the triangle comes from tying the inner count to the current row.
Done?
You can build grids and shapes from loops inside loops. The last chapter of Part 4 — Loop patterns — names the jobs loops do most: adding up, counting, searching, and flagging.