Lesson 16 of 21 · 2 min
Nested Loops — A Loop Inside a Loop
The WHY — Why Nest Loops?
Sometimes you need to process combinations or grids. To print every seat in a theater (rows 1-3, seats A-C), you need to go through every row AND every seat — that requires loops inside loops.
# Print a multiplication table
for row in range(1, 4): # outer loop: row goes 1, 2, 3
for col in range(1, 4): # inner loop: col goes 1, 2, 3 for EACH row
product = row * col # calculate row × col
print(f"{row}×{col}={product}", end=" ") # print on same line
print() # after inner loop finishes, start new line
Output: 1×1=1 1×2=2 1×3=3 2×1=2 2×2=4 2×3=6 3×1=3 3×2=6 3×3=9
The inner loop runs completely (1, 2, 3) for every single iteration of the outer loop. Total: 3 × 3 = 9 iterations.
