Python Module 3 – Control flow: decisions, loops and pattern matching
Nested loops and pattern printing
Trace nested loops in Python, count how often the inner block runs, and build star pyramids, diamonds, Floyd's and Pascal's triangles from a formula per row.
What you will learn
- Trace nested loops and count how often the inner block runs
- Build star and number patterns row by row from a formula for row i
- Generate Pascal's and Floyd's triangles with an inner loop
- Format table columns with rjust() and show trailing spaces with repr()
- Use return or a flag to stop a nested search at its first find
Before you start
What you’ll learn · Before you start
What you will learn
- Trace nested loops and count how often the inner block runs
- Build star and number patterns row by row from a formula for row i
- Generate Pascal's and Floyd's triangles with an inner loop
- Format table columns with rjust() and show trailing spaces with repr()
- Use return or a flag to stop a nested search at its first find
Before you start
On this page
A hall of 3 rows with 4 seats in each needs 12 seat labels, and a loop inside a loop writes them all. A loop’s block can contain another loop. The inner loop then runs from start to finish on every pass of the outer one. That is how programs walk through anything with rows and columns, such as seats in a hall, cells of a table or pixels of an image, and it is the idea behind star and number patterns, a classic way to practise loop control.
Below you can step through the seat labels pass by pass and count how often the inner block runs. You will build
pyramids, diamonds and the triangles of Floyd and Pascal from a formula for row i, line up the columns of a table,
and stop a nested search as soon as it finds what it wants.
The inner loop runs in full on every pass of the outer loop
This program labels the seats of a small hall with three rows of four seats, and counts how often the inner block runs.
Step through it and watch the two flags: the outer loop’s under "ABC", the inner loop’s under the numbers of its
range:
Program · seat_labels.py
runs = 0
for row in "ABC":
labels = []
for seat in range(1, 5):
labels.append(row + str(seat))
runs += 1
print(" ".join(labels))
print("The inner block ran", runs, "times: 3 rows x 4 seats")
runs = 0
for row in range(1, 5):
for seat in range(row):
runs += 1
print("A triangle of 4 rows runs it", runs, "times: 1 + 2 + 3 + 4") Variables
- just taken by the loop
- changed in this step
- passed by the loop
- read next
- where the loop stopped
- the stop value, never given
Printed so far
Nothing printed yetA1 A2 A3 A4 B1 B2 B3 B4 C1 C2 C3 C4 The inner block ran 12 times: 3 rows x 4 seats A triangle of 4 rows runs it 10 times: 1 + 2 + 3 + 4
Every step was recorded from a run with Python 3.14.8 on macOS 26 arm64.
The drawing shows the variables when the program ends, and the program's 83 steps are listed below.
Change the program and run it here. Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Every step as text
- Start. No line has run yet, so there are no variables. Python starts with line 1.
- Line 1.
runs = 0setsrunsto0. - Line 2.
for row in "ABC":takes the character at position 0 of"ABC":rowis'A'. - Line 3.
labels = []makeslabelsa list of 0 items. - Line 4.
for seat in range(1, 5):gives its first number:seatis1. - Line 5.
labels.append(row + str(seat))adds'A1'to the end oflabels. - Line 6.
runs += 1changesrunsfrom0to1. - Line 4.
for seat in range(1, 5):gives the next number:seatis2. - Line 5.
labels.append(row + str(seat))adds'A2'to the end oflabels. - Line 6.
runs += 1changesrunsfrom1to2. - Line 4.
for seat in range(1, 5):gives the next number:seatis3. - Line 5.
labels.append(row + str(seat))adds'A3'to the end oflabels. - Line 6.
runs += 1changesrunsfrom2to3. - Line 4.
for seat in range(1, 5):gives the next number:seatis4. - Line 5.
labels.append(row + str(seat))adds'A4'to the end oflabels. - Line 6.
runs += 1changesrunsfrom3to4. - Line 4.
for seat in range(1, 5):has no number left: a range stops before its stop value,5, so the loop ends. - Line 7.
print(" ".join(labels))printsA1 A2 A3 A4. - Line 2.
for row in "ABC":takes the character at position 1 of"ABC":rowis'B'. - Line 3.
labels = []setslabelsto[](it was['A1', 'A2', 'A3', 'A4']). - Line 4.
for seat in range(1, 5):gives its first number:seatis1. Key point The outer loop has moved on to "B", and the inner loop starts again from seat 1. It runs in full on every pass of the outer loop. - Line 5.
labels.append(row + str(seat))adds'B1'to the end oflabels. - Line 6.
runs += 1changesrunsfrom4to5. - Line 4.
for seat in range(1, 5):gives the next number:seatis2. - Line 5.
labels.append(row + str(seat))adds'B2'to the end oflabels. - Line 6.
runs += 1changesrunsfrom5to6. - Line 4.
for seat in range(1, 5):gives the next number:seatis3. - Line 5.
labels.append(row + str(seat))adds'B3'to the end oflabels. - Line 6.
runs += 1changesrunsfrom6to7. - Line 4.
for seat in range(1, 5):gives the next number:seatis4. - Line 5.
labels.append(row + str(seat))adds'B4'to the end oflabels. - Line 6.
runs += 1changesrunsfrom7to8. - Line 4.
for seat in range(1, 5):has no number left: a range stops before its stop value,5, so the loop ends. - Line 7.
print(" ".join(labels))printsB1 B2 B3 B4. - Line 2.
for row in "ABC":takes the character at position 2 of"ABC":rowis'C'. - Line 3.
labels = []setslabelsto[](it was['B1', 'B2', 'B3', 'B4']). - Line 4.
for seat in range(1, 5):gives its first number:seatis1. - Line 5.
labels.append(row + str(seat))adds'C1'to the end oflabels. - Line 6.
runs += 1changesrunsfrom8to9. - Line 4.
for seat in range(1, 5):gives the next number:seatis2. - Line 5.
labels.append(row + str(seat))adds'C2'to the end oflabels. - Line 6.
runs += 1changesrunsfrom9to10. - Line 4.
for seat in range(1, 5):gives the next number:seatis3. - Line 5.
labels.append(row + str(seat))adds'C3'to the end oflabels. - Line 6.
runs += 1changesrunsfrom10to11. - Line 4.
for seat in range(1, 5):gives the next number:seatis4. - Line 5.
labels.append(row + str(seat))adds'C4'to the end oflabels. - Line 6.
runs += 1changesrunsfrom11to12. - Line 4.
for seat in range(1, 5):has no number left: a range stops before its stop value,5, so the loop ends. - Line 7.
print(" ".join(labels))printsC1 C2 C3 C4. - Line 2.
for row in "ABC":finds no character at position 3 of"ABC"(it has 3 characters), so the loop ends. - Line 8.
print("The inner block ran", runs, "times: 3 rows x 4 seats")printsThe inner block ran 12 times: 3 rows x 4 seats. The inner block ran 3 × 4 = 12 times: the product of the two loop sizes. - Line 10.
runs = 0setsrunsto0(it was12). - Line 11.
for row in range(1, 5):gives its first number:rowis1. - Line 12.
for seat in range(row):gives its first number:seatis0. Now the inner range depends on the outer variable:range(row)gives 1 number on row 1, 2 on row 2, and so on. - Line 13.
runs += 1changesrunsfrom0to1. - Line 12.
for seat in range(row):has no number left: a range stops before its stop value,1, so the loop ends. - Line 11.
for row in range(1, 5):gives the next number:rowis2. - Line 12.
for seat in range(row):gives its first number:seatis0. - Line 13.
runs += 1changesrunsfrom1to2. - Line 12.
for seat in range(row):gives the next number:seatis1. - Line 13.
runs += 1changesrunsfrom2to3. - Line 12.
for seat in range(row):has no number left: a range stops before its stop value,2, so the loop ends. - Line 11.
for row in range(1, 5):gives the next number:rowis3. - Line 12.
for seat in range(row):gives its first number:seatis0. - Line 13.
runs += 1changesrunsfrom3to4. - Line 12.
for seat in range(row):gives the next number:seatis1. - Line 13.
runs += 1changesrunsfrom4to5. - Line 12.
for seat in range(row):gives the next number:seatis2. - Line 13.
runs += 1changesrunsfrom5to6. - Line 12.
for seat in range(row):has no number left: a range stops before its stop value,3, so the loop ends. - Line 11.
for row in range(1, 5):gives the next number:rowis4. - Line 12.
for seat in range(row):gives its first number:seatis0. - Line 13.
runs += 1changesrunsfrom6to7. - Line 12.
for seat in range(row):gives the next number:seatis1. - Line 13.
runs += 1changesrunsfrom7to8. - Line 12.
for seat in range(row):gives the next number:seatis2. - Line 13.
runs += 1changesrunsfrom8to9. - Line 12.
for seat in range(row):gives the next number:seatis3. - Line 13.
runs += 1changesrunsfrom9to10. - Line 12.
for seat in range(row):has no number left: a range stops before its stop value,4, so the loop ends. - Line 11.
for row in range(1, 5):has no number left: a range stops before its stop value,5, so the loop ends. - Line 14.
print("A triangle of 4 rows runs it", runs, "times: 1 + 2 + 3 + 4")printsA triangle of 4 rows runs it 10 times: 1 + 2 + 3 + 4. That was the last line, so the program ends. The triangle ran the inner block 1 + 2 + 3 + 4 = 10 times. When the inner size changes from row to row, add the sizes up.
The order in which the inner block of seat_labels.py runs
Text description of the diagram
The diagram is a grid with three rows, A, B and C, and four seats in each row. Each seat is numbered with the run of the inner block that labels it.
- Row A: A1 is run 1, A2 run 2, A3 run 3 and A4 run 4.
- Row B: B1 is run 5, B2 run 6, B3 run 7 and B4 run 8.
- Row C: C1 is run 9, C2 run 10, C3 run 11 and C4 run 12.
The inner loop goes through all four seats of a row before the outer loop moves on to the next row, so the inner block runs 3 × 4 = 12 times in all.
The outer loop takes "A", and the inner loop goes through seats 1 to 4. Only then does the outer loop move on to
"B", and the inner loop starts again from seat 1. So the inner block runs 3 × 4 = 12 times: the number of runs is
the product of the two loop sizes. With 1,000 rows of 1,000 items, that is a million runs, which is worth knowing
before you nest loops over large data.
When the inner loop’s size depends on the outer variable, add up the sizes instead. In the triangle at the end of the
program, row 1 has one pass, row 2 two, and so on, so 4 rows make 1 + 2 + 3 + 4 = 10 runs; n rows make
n × (n + 1) ÷ 2.
Key idea
The inner loop starts again on every pass of the outer loop, so its block runs (outer size) × (inner size) times, or the sum of the inner sizes when they change from row to row.
Checkpoint
Check: How often the inner block runs
Build each row as one string, then print it
Patterns made of characters are printed one row at a time. The direct way uses an inner loop that prints one star at a
time, with end="" so that print() does not start a new line after each star:
n = 4
for i in range(1, n + 1):
for j in range(i):
print("*", end="")
print()
for i in range(1, n + 1):
print("*" * i) Output
* ** *** **** * ** *** ****
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 stars_by_hand.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Both halves print the same triangle. In the second, "*" * i repeats the star i times and does the inner loop’s job
in one expression. Building the row as a string first and printing it once is shorter, and it is easier to check,
because the whole row is one value you can look at. For rows made of several parts, collect them in a list and join
them: " ".join(["1", "2", "3"]) gives "1 2 3".
Checkpoint
Check: One string per row
Work out row i before you write the loop
A reliable way to write any pattern is to describe row i with a formula before writing a loop. For a pyramid of
n = 4 rows, count the spaces before the stars and the stars on each row:
Row i |
Spaces | Stars |
|---|---|---|
| 1 | 3 | 1 |
| 2 | 2 | 3 |
| 3 | 1 | 5 |
| 4 | 0 | 7 |
The spaces go down by one per row and the stars go up by two, so row i has n - i spaces and 2 * i - 1 stars.
With the formula, every variant is a different range():
n = 4
print("Pyramid")
for i in range(1, n + 1):
print(" " * (n - i) + "*" * (2 * i - 1))
print("Inverted")
for i in range(n, 0, -1):
print(" " * (n - i) + "*" * (2 * i - 1))
print("Diamond")
for i in range(1, n + 1):
print(" " * (n - i) + "*" * (2 * i - 1))
for i in range(n - 1, 0, -1):
print(" " * (n - i) + "*" * (2 * i - 1)) Output
Pyramid * *** ***** ******* Inverted ******* ***** *** * Diamond * *** ***** ******* ***** *** *
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 pyramids.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
The inverted pyramid uses the same formula with i counting down, range(n, 0, -1). The diamond is the pyramid
followed by the inverted pyramid without its first row, range(n - 1, 0, -1), so that the widest row is printed only
once. The left padding is all that centres a row: nothing is printed after the stars.
Checkpoint
Check: A formula for row i
Floyd’s and Pascal’s triangles carry numbers from row to row
Number patterns follow the same plan, with the numbers worked out in the inner loop:
import math
n = 5
print("Floyd's triangle")
number = 1
for row in range(1, n + 1):
cells = []
for _ in range(row):
cells.append(str(number))
number += 1
print(" ".join(cells))
print("Pascal's triangle")
row = [1]
differences = 0
for i in range(n):
texts = []
for value in row:
texts.append(str(value))
print(" " * (n - 1 - i) + " ".join(texts))
for k in range(len(row)):
if row[k] != math.comb(i, k):
differences += 1
next_row = [1]
for k in range(1, len(row)):
next_row.append(row[k - 1] + row[k])
next_row.append(1)
row = next_row
print("Numbers that differ from math.comb(i, k):", differences) Output
Floyd's triangle
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Pascal's triangle
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Numbers that differ from math.comb(i, k): 0
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 number_triangles.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Floyd’s triangle puts the counting numbers into rows of 1, 2, 3 … numbers. The counter number is created before
both loops, so it keeps counting from one row to the next. The inner loop’s variable is never used, so it has the
conventional name _.
Pascal’s triangle starts with a row holding a single 1. Each new row begins and ends with 1, and each number in
between is the sum of the two numbers above it, row[k - 1] + row[k]. Step through the inner loop that turns the row
1 3 3 1 into the next one:
Program · pascal_step.py
row = [1, 3, 3, 1]
next_row = [1]
for k in range(1, len(row)):
next_row.append(row[k - 1] + row[k])
next_row.append(1)
print(next_row) Variables
- just taken by the loop
- changed in this step
- passed by the loop
- read next
- where the loop stopped
- the stop value, never given
Printed so far
Nothing printed yet[1, 4, 6, 4, 1]
Every step was recorded from a run with Python 3.14.8 on macOS 26 arm64.
The drawing shows the variables when the program ends, and the program's 12 steps are listed below.
Change the program and run it here. Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Every step as text
- Start. No line has run yet, so there are no variables. Python starts with line 1.
- Line 1.
row = [1, 3, 3, 1]makesrowa list of 4 items. - Line 2.
next_row = [1]makesnext_rowa list of 1 item. - Line 3.
for k in range(1, len(row)):gives its first number:kis1. - Line 4.
next_row.append(row[k - 1] + row[k])adds4to the end ofnext_row.kis 1, so this addsrow[0] + row[1], 1 + 3 = 4: the two numbers above the new one. - Line 3.
for k in range(1, len(row)):gives the next number:kis2. - Line 4.
next_row.append(row[k - 1] + row[k])adds6to the end ofnext_row. - Line 3.
for k in range(1, len(row)):gives the next number:kis3. - Line 4.
next_row.append(row[k - 1] + row[k])adds4to the end ofnext_row. - Line 3.
for k in range(1, len(row)):has no number left: a range stops before its stop value,4, so the loop ends. - Line 5.
next_row.append(1)adds1to the end ofnext_row. Every row of the triangle begins and ends with 1, so the loop works out only the numbers in between, and the last 1 is added after it. - Line 6.
print(next_row)prints[1, 4, 6, 4, 1]. That was the last line, so the program ends. Key point 1, 4, 6, 4 and 1 are the next row: the numbers of ways to choose 0, 1, 2, 3 or 4 items out of 4.
The numbers are the binomial coefficient: The number of ways to choose k items out of n when order does not matter. math.comb(n, k) computes it, and row n of Pascal's triangle lists it for k = 0 to n: row 4 is 1 4 6 4 1., so number_triangles.py compares
every one of them with math.comb(i, k), the standard library’s count of the ways to choose k of i items, and finds no
difference. The rows line up only while every number has one digit: the sixth row, 1 5 10 10 5 1, would be wider
than the spacing allows.
Checkpoint
Check: Floyd's and Pascal's triangles
rjust() lines up the columns of a table
Numbers of different widths make ragged columns. str.rjust(width) pads a string with spaces on the left up to
width characters, so every column ends in the same place; ljust() pads on the right and center() on both sides.
For example, "6".rjust(3) is " 6" and "36".rjust(3) is " 36": both end in the third character.
size = 6
cell = len(str(size * size)) + 1 # the widest product and a space
label = len(str(size)) # the widest row number
line = "x".rjust(label) + " |"
for col in range(1, size + 1):
line += str(col).rjust(cell)
print(line)
print("-" * len(line))
for row in range(1, size + 1):
line = str(row).rjust(label) + " |"
for col in range(1, size + 1):
line += str(row * col).rjust(cell)
print(line) Output
x | 1 2 3 4 5 6 --------------------- 1 | 1 2 3 4 5 6 2 | 2 4 6 8 10 12 3 | 3 6 9 12 15 18 4 | 4 8 12 16 20 24 5 | 5 10 15 20 25 30 6 | 6 12 18 24 30 36
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 times_grid.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
The width of a column comes from the widest product, size * size, plus one space to separate the columns, and the
row numbers get the width of the largest one, so the grid stays aligned for any size. Each row is built by its inner
loop and printed once. With size = 6 the widest product is 36, two digits, so every cell is three characters wide.
Checkpoint
Check: Columns with rjust()
break leaves only the inner loop
break leaves only the innermost loop. Searches in a grid often need to stop both loops, and this attempt does not.
Step through it and watch the outer flag after each break:
Program · free_seats_break.py
hall = ["XX.XX", "X..XX", "XXX.."] # X is taken, . is free
# Wanted: the first row with two free seats side by side
for r, row in enumerate(hall):
for s in range(len(row) - 1):
if row[s] == "." and row[s + 1] == ".":
print("Found: row", r, "seats", s, "and", s + 1)
break Variables
- just taken by the loop
- changed in this step
- passed by the loop
- read next
- where the loop stopped
- the stop value, never given
Printed so far
Nothing printed yetFound: row 1 seats 1 and 2 Found: row 2 seats 3 and 4
Every step was recorded from a run with Python 3.14.8 on macOS 26 arm64.
The drawing shows the variables when the program ends, and the program's 31 steps are listed below.
Change the program and run it here. Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Every step as text
- Start. No line has run yet, so there are no variables. Python starts with line 1.
- Line 1.
hall = ["XX.XX", "X..XX", "XXX.."]makeshalla list of 3 items. - Line 4.
for r, row in enumerate(hall):takes the item at position 0 ofhall, numbered 0:ris0androwis'XX.XX'. - Line 5.
for s in range(len(row) - 1):gives its first number:sis0. - Line 6.
row[s] == "." and row[s + 1] == "."is false (rowis'XX.XX'andsis0), so Python skips the block underif row[s] == "." and row[s + 1] == ".":. - Line 5.
for s in range(len(row) - 1):gives the next number:sis1. - Line 6.
row[s] == "." and row[s + 1] == "."is false (rowis'XX.XX'andsis1), so Python skips the block underif row[s] == "." and row[s + 1] == ".":. - Line 5.
for s in range(len(row) - 1):gives the next number:sis2. - Line 6.
row[s] == "." and row[s + 1] == "."is false (rowis'XX.XX'andsis2), so Python skips the block underif row[s] == "." and row[s + 1] == ".":. - Line 5.
for s in range(len(row) - 1):gives the next number:sis3. - Line 6.
row[s] == "." and row[s + 1] == "."is false (rowis'XX.XX'andsis3), so Python skips the block underif row[s] == "." and row[s + 1] == ".":. - Line 5.
for s in range(len(row) - 1):has no number left: a range stops before its stop value,4, so the loop ends. - Line 4.
for r, row in enumerate(hall):takes the item at position 1 ofhall, numbered 1:ris1androwis'X..XX'. - Line 5.
for s in range(len(row) - 1):gives its first number:sis0. - Line 6.
row[s] == "." and row[s + 1] == "."is false (rowis'X..XX'andsis0), so Python skips the block underif row[s] == "." and row[s + 1] == ".":. - Line 5.
for s in range(len(row) - 1):gives the next number:sis1. - Line 6.
row[s] == "." and row[s + 1] == "."is true (rowis'X..XX'andsis1), so the block underif row[s] == "." and row[s + 1] == ".":runs. - Line 7.
print("Found: row", r, "seats", s, "and", s + 1)printsFound: row 1 seats 1 and 2. - Line 8.
breakleaves the loop at once, without reading the items it has not reached. The bug Thisbreakleaves only the inner loop, the one over seats. The outer loop is still running, so it moves on to the next row. - Line 4.
for r, row in enumerate(hall):takes the item at position 2 ofhall, numbered 2:ris2androwis'XXX..'. - Line 5.
for s in range(len(row) - 1):gives its first number:sis0. - Line 6.
row[s] == "." and row[s + 1] == "."is false (rowis'XXX..'andsis0), so Python skips the block underif row[s] == "." and row[s + 1] == ".":. - Line 5.
for s in range(len(row) - 1):gives the next number:sis1. - Line 6.
row[s] == "." and row[s + 1] == "."is false (rowis'XXX..'andsis1), so Python skips the block underif row[s] == "." and row[s + 1] == ".":. - Line 5.
for s in range(len(row) - 1):gives the next number:sis2. - Line 6.
row[s] == "." and row[s + 1] == "."is false (rowis'XXX..'andsis2), so Python skips the block underif row[s] == "." and row[s + 1] == ".":. - Line 5.
for s in range(len(row) - 1):gives the next number:sis3. - Line 6.
row[s] == "." and row[s + 1] == "."is true (rowis'XXX..'andsis3), so the block underif row[s] == "." and row[s + 1] == ".":runs. - Line 7.
print("Found: row", r, "seats", s, "and", s + 1)printsFound: row 2 seats 3 and 4. - Line 8.
breakleaves the loop at once, without reading the items it has not reached. - Line 4.
for r, row in enumerate(hall):finds no item at position 3 ofhall(it has 3 items), so the loop ends. That was the last line, so the program ends. Two rows were reported where one was wanted. To stop both loops, return from a function or set a flag, as the next program does.
The goal was the first row with two free seats side by side, but the program reports two rows. The break ended the
search in row 1, and then the outer loop simply went on to row 2. There are two clear ways to stop everything:
hall = ["XX.XX", "X..XX", "XXX.."] # X is taken, . is free
def first_pair(hall):
for r, row in enumerate(hall):
for s in range(len(row) - 1):
if row[s] == "." and row[s + 1] == ".":
return r, s
return None
print("With return:", first_pair(hall))
found = None
for r, row in enumerate(hall):
for s in range(len(row) - 1):
if row[s] == "." and row[s + 1] == ".":
found = (r, s)
break
if found is not None:
break
print("With a flag:", found) Output
With return: (1, 1) With a flag: (1, 1)
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 free_seats_fixed.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
- Return from a function.
returnends the function at once, however deeply the loops are nested; returningNoneafter the loops says that nothing was found. This is usually the clearest version. - A flag. Set a variable when the inner loop finds the answer, and test it in the outer loop to
breakthere too. Such a variable is called a flag: A variable, usually True or False, that one part of a program sets to record that something happened, so that another part can act on it, such as found = True to make an outer loop stop too..
The else clause of the inner loop can also tell the outer loop that nothing was found, but code written that way is
harder to follow than either version above.
Checkpoint
Check: Stopping a nested search
repr() shows the spaces a row ends with
When a checker compares your output with the expected text, as this lesson’s exercise does, spaces at the end of a
row count. print() does not show them, but repr() does:
n = 3
for i in range(1, n + 1):
print(repr(("*" * (2 * i - 1)).center(2 * n - 1)))
print(repr("*".center(4)), repr("ab".center(5)))
for j in range(1, 4):
print(j, end=" ")
print("|") Output
' * ' ' *** ' '*****' ' * ' ' ab ' 1 2 3 |
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 hidden_spaces.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
center() pads both sides, so every row except the widest ends in spaces. When the padding is an odd number of
spaces, one side gets the extra one, and which side depends on the lengths involved: the fourth line of output shows
that "*".center(4) puts one space before the star and two after it, while "ab".center(5) puts two before and one
after.
Printing with end=" " leaves a space after the last number too, just before the |. To get exact rows, build them
with left padding only (" " * (n - i) + ...), join the parts with " ".join(), or remove what is left at the end
with .rstrip(). Those leftover spaces are trailing whitespace: Spaces or tabs at the end of a line. print() does not show them, but an exact comparison of output counts them; repr() makes them visible and rstrip() removes them..
Checkpoint
Check: Spaces at the end of a row
Practise: return the rows of a pattern
The exercise asks for a pyramid, a diamond or Pascal’s triangle as a list of strings instead of printed lines. Its
sample tests compare every row character by character, spaces included, so when one fails, print the rows with
repr() to see what differs.
Exercise · Medium · Python
Return the rows of a pyramid, a diamond or Pascal's triangle
Write pattern(kind, n), which returns the rows of a pattern as a list of strings instead of printing them. kind is "pyramid", "diamond" or "pascal", and n is a whole number, 0 or more. The tests compare every string exactly, spaces included.
"pyramid":nrows. Rowi(counting from 1) has2 * i - 1stars, after just enough spaces to centre it above the bottom row, and nothing after the stars."diamond": the pyramid followed by its rows in reverse order without repeating the widest row, so2 * n - 1rows."pascal": the firstnrows of Pascal's triangle, the numbers of a row separated by single spaces, with no spaces before or after them. Each row starts and ends with 1, and every other number is the sum of the two numbers above it.- For
n = 0, every kind returns[]. Any otherkindraisesValueError: writeraise ValueError(f"unknown kind: {kind}").
These are the rows of pattern("pyramid", 3), of pattern("diamond", 2) and of pattern("pascal", 4), one string per line (the first row of the pyramid is two spaces and a star):
*
***
*****
*
***
*
1
1 1
1 2 1
1 3 3 1Starter code · patterns.py
def pattern(kind, n):
"""Return the n rows of a "pyramid", "diamond" or "pascal" pattern."""
rows = []
return rows The sample tests · test_patterns.py
from patterns import pattern
def test_pyramid():
"""builds a pyramid with no spaces at the ends of its rows"""
assert pattern("pyramid", 1) == ["*"]
assert pattern("pyramid", 3) == [" *", " ***", "*****"]
assert pattern("pyramid", 4) == [" *", " ***", " *****", "*******"]
def test_diamond():
"""puts the pyramid on its mirror image, sharing the widest row"""
assert pattern("diamond", 1) == ["*"]
assert pattern("diamond", 2) == [" *", "***", " *"]
assert pattern("diamond", 3) == [" *", " ***", "*****", " ***", " *"]
def test_pascal():
"""builds the rows of Pascal's triangle"""
assert pattern("pascal", 1) == ["1"]
assert pattern("pascal", 4) == ["1", "1 1", "1 2 1", "1 3 3 1"]
assert pattern("pascal", 6)[-1] == "1 5 10 10 5 1"
def test_zero_rows():
"""returns no rows for n = 0"""
assert pattern("pyramid", 0) == []
assert pattern("diamond", 0) == []
assert pattern("pascal", 0) == []
def test_unknown_kind():
"""raises ValueError for any other kind"""
try:
pattern("square", 3)
except ValueError:
return
assert False, "pattern('square', 3) should raise ValueError" A hint
Write down row i first: for a pyramid of n rows it is n - i spaces and then 2 * i - 1 stars, so a single loop over range(1, n + 1) can append " " * (n - i) + "*" * (2 * i - 1) to the list. For Pascal's triangle, keep the current row as a list of numbers, build the next row from it with an inner loop, and store " ".join(...) of the numbers as text.
Results of the sample tests
| Test | Result | Details |
|---|
What your code printed
The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.
Afterwards, take the practice round. It picks the ideas of this lesson that you have not mastered yet and shows the reasoning behind every answer:
Practice that adapts to you
Practise this lesson
17 questions about 7 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.
Interview questions
Fresher · How many times does the innermost line of two nested loops run?
It runs once for every pass of the inner loop, on every pass of the outer loop. When the inner loop’s size does not
depend on the outer variable, that is the product of the two sizes: 3 rows of 4 seats give 12 runs, and 1,000 by
1,000 gives a million. When the inner size grows with the outer variable, as with for j in range(i) inside
for i in range(1, n + 1), add the sizes up: 1 + 2 + … + n, which is n(n + 1)/2, so 10 for n = 4 and 500,500 for
n = 1,000. Both counts grow with the square of n, so doubling the input makes the work about four times larger. That
is why two nested loops over large lists are slow, and why a set or a dictionary lookup often replaces the inner loop.
Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.
-
Fresher to mid
A nightly job finds the customers who are on both of two mailing lists, of 40,000 and 60,000 addresses, with one for loop inside another. As the lists grow it gets slower every month. Estimate the work it does, explain why it grows so fast, and rewrite it.
-
Fresher to mid
A cinema booking function searches a 30-row hall for the first row with 4 free seats side by side, with two nested loops and a break, and books them. Testers find that it sometimes books seats in two rows at once. Explain why, fix it, and describe the tests you would add.
Key takeaways
- The inner loop runs completely on every pass of the outer loop; the inner block runs (outer size) × (inner size) times, or the sum of the inner sizes when they change from row to row.
- Build each row as one string, with repetition (
"*" * k) or" ".join(parts), and print it once. - Before coding a pattern, write down the spaces and characters of row
ias formulas such asn - iand2 * i - 1. - Floyd’s triangle keeps one counter across all its rows, and each inner number of Pascal’s triangle is the sum of the two numbers above it.
rjust(),ljust()andcenter()align text;center()andend=" "leave spaces at the ends of rows.breakleaves only the inner loop: to stop a nested search, return from a function or use a flag.
Terms in this lesson
- binomial coefficient
- The number of ways to choose k items out of n when order does not matter. math.comb(n, k) computes it, and row n of Pascal's triangle lists it for k = 0 to n: row 4 is 1 4 6 4 1.
- flag
- A variable, usually True or False, that one part of a program sets to record that something happened, so that another part can act on it, such as found = True to make an outer loop stop too.
- trailing whitespace
- Spaces or tabs at the end of a line. print() does not show them, but an exact comparison of output counts them; repr() makes them visible and rstrip() removes them.
References
- The Python Tutorial: for Statements (Python Software Foundation)
- The Python Tutorial: break and continue Statements (Python Software Foundation)
- Built-in Types: Common Sequence Operations (Python Software Foundation)
- Built-in Types: str.join (Python Software Foundation)
- Built-in Types: str.center (Python Software Foundation)
- Built-in Types: str.rjust (Python Software Foundation)
- math: math.comb (Python Software Foundation)
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress