Loops inside loops
🌍 In real life. Look at a clock: for every single step of the hour hand, the minute hand goes all the way round. Or think of a multiplication table: for each row, you go across every column before moving down to the next row.
That's a loop inside a loop.
The idea in one sentence: in a nested loop, the inner loop runs all the way through, from start to finish, for every lap of the outer loop.
Its words:
- outer loop: the loop on the outside, like the rows
- inner loop: the loop inside its block, like the columns
end=" ": makesprintend with a space instead of a new line
Step by step, for 2 rows and 3 columns:
- The outer loop sets row = 0. The inner loop runs col = 0, 1, 2.
- The inner loop is done, so the outer loop moves on: row = 1.
- The inner loop starts again from the beginning: col = 0, 1, 2.
- 2 rows × 3 columns = 6 prints in all.
for row in range(2):
for col in range(3):
print(row, col)print normally ends with a new line. print(x, end=" ") ends with a space instead, so the next print stays on the same line. A plain print() then finishes the row. Together they draw tables:
for row in range(1, 4):
for col in range(1, 4):
print(row * col, end=" ")
print()The inner loop can use the outer loop's variable. Here row 1 gets one star, row 2 gets two, and so on:
for row in range(1, 5):
for i in range(row):
print("*", end="")
print()What it costs. The inner block runs outer laps × inner laps times. A 10 × 10 table is 100 prints, but 1,000 × 1,000 is a million, and 10,000 × 10,000 is a hundred million. Nested loops get slow quickly, which is why later chapters look for ways to avoid them.
Mistakes and edge cases.
- The row's print() at the wrong depth. Indented inside the inner loop, it puts every value on its own line. It belongs to the outer loop, after the inner one.
- The same name for both loops.
for i ...insidefor i ...overwrites the outeri, which makes the outer loop confusing to follow. Userowandcol. - Forgetting end=. Without it, each value goes on its own line and the table falls apart.
- The wrong variable in the inner range.
range(row)andrange(cols)make very different shapes: a triangle or a rectangle.
Quiz
What does this print?
for a in range(2): for b in range(2): print(a, b)The outer loop is
for i in range(3):and the inner loop isfor j in range(4):. How many times does the inner print run?- 12
- 7
- 4
What does this print?
for i in range(1, 3): for ch in "ab": print(ch * i)What does this print?
count = 0 for i in range(3): for j in range(i): count += 1 print(count)Which line has a mistake?
for i in range(2): for j in range(2): print(i, j)
Coding tasks
Ask for a whole number
n. Print a square of#signs that isnwide andntall.Ask for a whole number
n. Print annbynmultiplication table. Put a space after each number. Forn = 3:1 2 3 2 4 6 3 6 9Ask for a whole number
n. Print a number triangle: the first line is1, the second1 2, and so on up to1 2 … n.