19. Nested loops
A loop repeats a block. What if that block holds another loop? That's a nested loop: the inner one runs fully on every turn of the outer one. They build grids, tables, anything with rows and columns.
A loop inside a loop
Put one for inside another. The inner loop finishes
before the outer one moves:
for outer in range(1, 4):
for inner in range(1, 3):
print(outer, inner)Output:
1 1
1 2
2 1
2 2
3 1
3 2
Follow the order. While outer is 1, the
inner loop runs (1, 2). Then
outer becomes 2 and it runs again. That's
3 × 2 = 6 runs.
Give the two loop variables different names. If both
were i, the inner loop would clobber the outer counter.
row/col or i/j are
common pairs.
Building a row at a time
One value per line rarely suits a grid. The usual trick: the outer loop handles rows; the inner loop builds one string, printed when the row is done:
for row in range(1, 4):
line = ""
for col in range(1, 4):
line = line + str(row * col) + "\t"
print(line)Output (a 3×3 multiplication grid):
1 2 3
2 4 6
3 6 9
Notice line = "" sits inside the outer loop but
outside the inner one. It resets each row, fills up in the
inner loop, then prints.
Open exercises/19/01-grid.py. It prints a 3×3 grid.
Change only the two ranges to make it 5×5.
A triangle with a changing inner range
The inner range can depend on the outer variable. Run it
1 to row and you get a triangle:
for row in range(1, 5):
line = ""
for star in range(1, row + 1):
line = line + "*"
print(line)Output:
*
**
***
****
Row 1 runs range(1, 2) — once; row 4 runs
range(1, 5) — four times. The shape falls out of the
maths.
How many times does the body run?
Multiply the counts. An outer loop of 10 around an inner loop of 10
runs the body 10 × 10 = 100 times. It grows fast: three
loops of 100 each is a million runs. Powerful, so watch the numbers.
Homework
Homework files are in exercises/19/homework/.
Problem 1 — Rectangle of hashes
Open exercises/19/homework/01-rectangle.py. With nested
loops, print a rectangle of # 5 wide and 3 tall:
#####
#####
#####
Problem 2 — Coordinate pairs
Open exercises/19/homework/02-coords.py. Print every
(x, y) pair for x and y from 1 to
3, one per line: (1, 1), (1, 2), and so on.
Nine lines.
Problem 3 — Times table
Open exercises/19/homework/03-times-table.py. Print the
full multiplication grid from 1×1 to 5×5: five
rows of five tab-separated numbers each.
Challenge — Right triangle
Open exercises/19/homework/04-triangle.py. Print a
right-angled triangle of * 6 rows tall, where row
n has n stars. For a stretch, flip it upside
down (6 stars on the first row, 1 on the last).
Stuck or finished? Open the homework solutions page.