These are the notes for Python episode 9. Last episode, a for loop walked through one row of things. But the world comes in grids: rows of seats, weeks of days, rows and columns of a table. Today we put a loop inside a loop. You will learn nested loops, how indentation decides how often a line runs, a neat multiplication grid with f-string widths, star and number patterns with a recipe that works for any pattern, why break only leaves the inner loop (and the flag that fixes it), and why nested loops can get slow. Every example below runs as-is in the SyntaxPilot compiler, with its real output from Python 3.13.
The problem: copy-pasting a whole loop
A small cinema wants a label for every seat. One row is one for loop (episode 8); three rows, A, B and C, means pasting the loop three times:
for seat in range(1, 5):
print("A" + str(seat), end=" ")
print()
for seat in range(1, 5):
print("B" + str(seat), end=" ")
print()
for seat in range(1, 5):
print("B" + str(seat), end=" ")
print()
Output:
A1 A2 A3 A4
B1 B2 B3 B4
B1 B2 B3 B4
Row B twice, no row C: we pasted the loop and forgot to change the letter. And a real cinema has 10 rows of 12 seats.
str(seat)turns the number into text so+can join it to the letter (episode 2).print()with nothing inside just ends the line.
Why it failed: it's episode 7's copy-paste problem one level up. The loop solved repeating a line; now we are repeating the loop itself by hand. The three loops are identical except for the row letter, and the row letters
"ABC"are a sequence too.
Nested loops
Real-life example: the hands of a clock.
| On a clock | In Python |
|---|---|
| The hour hand moves one step | the outer loop moves to the next row: for row in "ABC": |
| For every hour, the minute hand goes all the way round | the inner loop runs completely for each row: for seat in range(1, 5): |
| 12 hours × 60 minutes = 720 ticks | 3 rows × 4 seats = 12 labels |
A nested loop is a loop inside another loop's body.
for row in "ABC":
for seat in range(1, 5):
print(row + str(seat), end=" ")
print()
Output:
A1 A2 A3 A4
B1 B2 B3 B4
C1 C2 C3 C4
The real cinema: change "ABC" to "ABCDEFGHIJ" and range(1, 5) to range(1, 13) → 120 labels (A1 … J12) from the same four lines.
Indentation decides how often a line runs
Move the print() all the way to the left:
for row in "ABC":
for seat in range(1, 5):
print(row + str(seat), end=" ")
print()
Output (one long line):
A1 A2 A3 A4 B1 B2 B3 B4 C1 C2 C3 C4
| Where the line is | How often it runs |
|---|---|
| inside the inner loop (8 spaces) | once per seat (12 times) |
| inside the outer loop only (4 spaces) | once per row (3 times) |
| at the left edge | once, in total |
Indent the print() one level too far (inside the inner loop) and every seat gets its own line.
Reading a nested loop
for row in "ABC": # outer: once per row
for seat in range(1, 5): # inner: all seats, for every row
print(..., end=" ") # once per seat
print() # once per row: new line
- Outer loop = rows, inner loop = columns.
- The inner body runs rows × columns times (3 × 4 = 12).
A neat multiplication grid
for i in range(1, 6):
for j in range(1, 6):
print(i * j, end=" ")
print()
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
It works, but the columns are ragged: 2 and 10 take different widths. An f-string width fixes it:
for i in range(1, 6):
for j in range(1, 6):
print(f"{i * j:4}", end="")
print()
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
{value:4} means "always use 4 characters": numbers are padded with spaces on the left (right-aligned). end="" because the padding already does the spacing. For text, {name:10} pads on the right (left-aligned).
Star patterns
Real-life example: Raju stacking chai glasses. A tray of 4 rows of 4 is a square; a festival display with 1 glass in row 1, 2 in row 2, … is a triangle; centre each row with empty space first and it's a pyramid.
Square
for row in range(4):
for col in range(4):
print("*", end=" ")
print()
* * * *
* * * *
* * * *
* * * *
Every row has the same number of columns, so the inner range is a fixed 4.
Right triangle
for row in range(1, 6):
for col in range(row):
print("*", end=" ")
print()
*
* *
* * *
* * * *
* * * * *
The key idea: the inner loop's range uses the outer loop's variable. Row 1 prints 1 star, row 5 prints 5.
Shortcut with string repetition (episode 5):
for row in range(1, 6):
print("* " * row)
Same output with one loop. Interviews usually ask for the nested version, so know both.
Number triangle
for row in range(1, 6):
for col in range(1, row + 1):
print(col, end=" ")
print()
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Each row counts up to its own row number: print the inner variable instead of a star.
A recipe for any pattern
- The outer loop does one round per row.
- For each row, ask: how many spaces come first? how many stars come after?
- Write the answers as formulas of
row.
A pyramid of n = 5 rows:
| Row | Picture | Spaces | Stars |
|---|---|---|---|
| 1 | * |
4 | 1 |
| 2 | *** |
3 | 3 |
| 3 | ***** |
2 | 5 |
| 4 | ******* |
1 | 7 |
| 5 | ********* |
0 | 9 |
| formula | n - row |
2 * row - 1 |
n = 5
for row in range(1, n + 1):
print(" " * (n - row) + "*" * (2 * row - 1))
*
***
*****
*******
*********
Change n to 10 and you get a 10-row pyramid for free.
break in a nested loop
Real-life example: Raju wants a ₹45 combo. Chai comes at ₹10, ₹20, ₹30; snacks at ₹15, ₹25, ₹35. Find the first chai + snack pair that costs exactly ₹45, then stop searching.
budget = 45
for chai in range(10, 31, 10):
for snack in range(15, 36, 10):
if chai + snack == budget:
print("Found: chai", chai, "+ snack", snack)
break
Output:
Found: chai 10 + snack 35
Found: chai 20 + snack 25
Found: chai 30 + snack 15
Three combos! break leaves only the loop it is in — the innermost one. The outer loop carries on with the next chai and finds another pair.
The fix is a flag: a True/False variable that remembers something happened.
budget = 45
found = False
for chai in range(10, 31, 10):
for snack in range(15, 36, 10):
if chai + snack == budget:
print("Found: chai", chai, "+ snack", snack)
found = True
break
if found:
break
Output: Found: chai 10 + snack 35 — both loops stopped. (In episode 13 you'll see an even cleaner way: put the search in a function and return.)
Nested loops multiply the work
count = 0
for i in range(1000):
for j in range(1000):
count += 1
print("Rounds:", count)
Output: Rounds: 1000000 — a million rounds in a fraction of a second.
Change both 1000s to 20000: that's 400,000,000 rounds, and the SyntaxPilot compiler stops it with Time Limit Exceeded (8-second limit). 20 times bigger on each side made the work 400 times bigger. Nested loops multiply, so they get slow very fast; episode 33 (performance and Big-O) measures this properly.
Common mistakes
| Mistake | What you see | Why | Fix |
|---|---|---|---|
print() at the left edge |
no error, everything on one line | the new line runs once, not once per row | indent print() inside the outer loop |
print() inside the inner loop |
no error, one item per line | the new line runs once per item | move it out one level |
print(i * j, end=" ") in a grid |
ragged columns | numbers have different widths | f"{i * j:4}" |
break in the inner loop |
no error, 3 combos instead of 1 | break leaves only the innermost loop |
a found flag + break the outer loop |
| 20,000 × 20,000 rounds | Time Limit Exceeded | nested loops multiply the work | smaller ranges, smarter algorithms |
range(row) with row starting at 0 |
an empty first line | range(0) is empty |
start rows at 1, or use row + 1 |
Mini project: cinema seat map
Rows A to E, seats 1 to 6; booked seats are given as text. Booked → X, free → the seat number, each line starting with the row letter.
# Mini project: cinema seat map
booked = "A3 B5 C1 C2 D4"
print(" SCREEN THIS WAY")
for row in "ABCDE":
print(row, end=" ")
for seat in range(1, 7):
if row + str(seat) in booked:
print("X", end=" ")
else:
print(seat, end=" ")
print()
Output:
SCREEN THIS WAY
A 1 2 X 4 5 6
B 1 2 3 4 X 6
C X X 3 4 5 6
D 1 2 3 X 5 6
E 1 2 3 4 5 6
row + str(seat) in booked uses in (episode 5) to check whether a label like "C2" appears in the booked text. (This works because seat numbers here are single digits; with 12 seats, "A1" would wrongly match inside "A12". Lists in episode 10 fix that.)
Extend it: count the free seats.
Solution
booked = "A3 B5 C1 C2 D4"
free = 0
for row in "ABCDE":
for seat in range(1, 7):
if row + str(seat) not in booked:
free += 1
print("Free seats:", free)
Output: Free seats: 25 (30 seats − 5 booked).
Practice
1. Inverted triangle: 5 stars down to 1.
Solution
for row in range(5, 0, -1):
for col in range(row):
print("*", end=" ")
print()
* * * * *
* * * *
* * *
* *
*
2. Right-aligned triangle (spaces first).
Solution
n = 5
for row in range(1, n + 1):
print(" " * (n - row) + "*" * row)
*
**
***
****
*****
3. Floyd's triangle: 1 / 2 3 / 4 5 6 / 7 8 9 10.
Solution
num = 1
for row in range(1, 5):
for col in range(row):
print(num, end=" ")
num += 1
print()
num lives outside both loops, so it keeps counting across rows.
4. A hollow 5 × 5 square.
Solution
n = 5
for row in range(n):
for col in range(n):
if row == 0 or row == n - 1 or col == 0 or col == n - 1:
print("*", end=" ")
else:
print(" ", end=" ")
print()
* * * * *
* *
* *
* *
* * * * *
Stars only on the border: first/last row or first/last column.
5. How many times does the body run? for i in range(4): for j in range(i): ...
Answer
0 + 1 + 2 + 3 = 6 times. The inner range depends on i, so it isn't simply 4 × 4.
Quick quiz
What does this print?
for i in range(3):
for j in range(2):
print("*", end="")
print()
A) 3 lines of ** B) 2 lines of *** C) ****** on one line D) 6 lines of *
Answer
A) 3 lines of **. The outer loop makes 3 rows; for each row the inner loop prints 2 stars, then print() starts a new line.
Interview questions
- How many times does the inner body of a nested loop run? Outer rounds × inner rounds when the inner range is fixed (n × m); when the inner range depends on the outer variable, add up each row's count (e.g. 1 + 2 + … + n = n(n+1)/2).
- How do you break out of two nested loops at once? Use a flag checked after the inner loop, put the loops in a function and
return, or use the inner loop'selsewithcontinuefollowed bybreakin the outer loop. - Why are nested loops slow on big inputs? The work multiplies: two nested loops over n items do about n² steps, so doubling n makes it four times slower. This is O(n²) time.
- How do you print a pyramid of n rows? For each row,
n - rowspaces and2 * row - 1stars. - What does
f"{x:4}"do? Formatsxin a field 4 characters wide; numbers are right-aligned, text left-aligned.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Nested loop | A loop inside another loop's body | for row ...: then for seat ...: |
| Outer loop | The loop on the outside; usually the rows | for row in "ABC": |
| Inner loop | The loop inside; runs completely for each outer round | for seat in range(1, 5): |
| Row / column | Horizontal line / vertical line of a grid | row B / seat 3 |
str() |
Converts a value to text | str(3) → "3" |
print() |
With nothing inside, just ends the line | new row of seats |
| Width (format) | Minimum characters an f-string value takes | f"{25:4}" → " 25" |
| Right-aligned | Padded with spaces on the left | numbers in the grid |
| Pattern | A picture made of characters, row by row | a star pyramid |
| String repetition | text * n repeats the text n times |
"* " * 3 → "* * * " |
| Formula of row | How many spaces/stars a row needs, using row |
2 * row - 1 |
| Flag | A True/False variable that remembers something happened |
found = True |
break (nested) |
Leaves only the innermost loop | the combo search |
| Time Limit Exceeded | The online compiler stopped a program that ran too long | 400 million rounds |
| O(n²) | Work grows with the square of the input size | two nested loops over n items |
Summary
- A nested loop is a loop inside a loop: the inner loop runs completely for every round of the outer one. Think outer = rows, inner = columns.
- Indentation decides how often a line runs: inner body once per item, outer body once per row, left edge once.
f"{x:4}"gives fixed-width, right-aligned columns.- Patterns: the inner range uses the outer variable; for any pattern, find the spaces and stars per row as formulas of
row. breakleaves only the innermost loop; use a flag to stop both.- The work is rows × columns, so nested loops get slow fast.
Next episode: lists.