Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

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.

  • Beginner
  • 15 minutes
  • Examples run with Python 3.14.8 and Pyodide 314.0.7
  • By MySmartCoPilot
Free lesson, Pro answers: 15 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

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:

Interactive · line by line Rows and seats, pass by pass Watch the two flags. The outer loop reads "ABC"; the inner loop reads range(1, 5) and starts again from 1 on every row.

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

After line 14: runs is 10; row is 4; labels is ['C1', 'C2', 'C3', 'C4']; seat is 3.runs10row4labels'C1'0'C2'1'C3'2'C4'3seat3
  • 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

A1 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.

Line run 14
Next line end
Loop pass –
Every step as text
  1. Start. No line has run yet, so there are no variables. Python starts with line 1.
  2. Line 1. runs = 0 sets runs to 0.
  3. Line 2. for row in "ABC": takes the character at position 0 of "ABC": row is 'A'.
  4. Line 3. labels = [] makes labels a list of 0 items.
  5. Line 4. for seat in range(1, 5): gives its first number: seat is 1.
  6. Line 5. labels.append(row + str(seat)) adds 'A1' to the end of labels.
  7. Line 6. runs += 1 changes runs from 0 to 1.
  8. Line 4. for seat in range(1, 5): gives the next number: seat is 2.
  9. Line 5. labels.append(row + str(seat)) adds 'A2' to the end of labels.
  10. Line 6. runs += 1 changes runs from 1 to 2.
  11. Line 4. for seat in range(1, 5): gives the next number: seat is 3.
  12. Line 5. labels.append(row + str(seat)) adds 'A3' to the end of labels.
  13. Line 6. runs += 1 changes runs from 2 to 3.
  14. Line 4. for seat in range(1, 5): gives the next number: seat is 4.
  15. Line 5. labels.append(row + str(seat)) adds 'A4' to the end of labels.
  16. Line 6. runs += 1 changes runs from 3 to 4.
  17. Line 4. for seat in range(1, 5): has no number left: a range stops before its stop value, 5, so the loop ends.
  18. Line 7. print(" ".join(labels)) prints A1 A2 A3 A4.
  19. Line 2. for row in "ABC": takes the character at position 1 of "ABC": row is 'B'.
  20. Line 3. labels = [] sets labels to [] (it was ['A1', 'A2', 'A3', 'A4']).
  21. Line 4. for seat in range(1, 5): gives its first number: seat is 1. 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.
  22. Line 5. labels.append(row + str(seat)) adds 'B1' to the end of labels.
  23. Line 6. runs += 1 changes runs from 4 to 5.
  24. Line 4. for seat in range(1, 5): gives the next number: seat is 2.
  25. Line 5. labels.append(row + str(seat)) adds 'B2' to the end of labels.
  26. Line 6. runs += 1 changes runs from 5 to 6.
  27. Line 4. for seat in range(1, 5): gives the next number: seat is 3.
  28. Line 5. labels.append(row + str(seat)) adds 'B3' to the end of labels.
  29. Line 6. runs += 1 changes runs from 6 to 7.
  30. Line 4. for seat in range(1, 5): gives the next number: seat is 4.
  31. Line 5. labels.append(row + str(seat)) adds 'B4' to the end of labels.
  32. Line 6. runs += 1 changes runs from 7 to 8.
  33. Line 4. for seat in range(1, 5): has no number left: a range stops before its stop value, 5, so the loop ends.
  34. Line 7. print(" ".join(labels)) prints B1 B2 B3 B4.
  35. Line 2. for row in "ABC": takes the character at position 2 of "ABC": row is 'C'.
  36. Line 3. labels = [] sets labels to [] (it was ['B1', 'B2', 'B3', 'B4']).
  37. Line 4. for seat in range(1, 5): gives its first number: seat is 1.
  38. Line 5. labels.append(row + str(seat)) adds 'C1' to the end of labels.
  39. Line 6. runs += 1 changes runs from 8 to 9.
  40. Line 4. for seat in range(1, 5): gives the next number: seat is 2.
  41. Line 5. labels.append(row + str(seat)) adds 'C2' to the end of labels.
  42. Line 6. runs += 1 changes runs from 9 to 10.
  43. Line 4. for seat in range(1, 5): gives the next number: seat is 3.
  44. Line 5. labels.append(row + str(seat)) adds 'C3' to the end of labels.
  45. Line 6. runs += 1 changes runs from 10 to 11.
  46. Line 4. for seat in range(1, 5): gives the next number: seat is 4.
  47. Line 5. labels.append(row + str(seat)) adds 'C4' to the end of labels.
  48. Line 6. runs += 1 changes runs from 11 to 12.
  49. Line 4. for seat in range(1, 5): has no number left: a range stops before its stop value, 5, so the loop ends.
  50. Line 7. print(" ".join(labels)) prints C1 C2 C3 C4.
  51. Line 2. for row in "ABC": finds no character at position 3 of "ABC" (it has 3 characters), so the loop ends.
  52. Line 8. print("The inner block ran", runs, "times: 3 rows x 4 seats") prints The 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.
  53. Line 10. runs = 0 sets runs to 0 (it was 12).
  54. Line 11. for row in range(1, 5): gives its first number: row is 1.
  55. Line 12. for seat in range(row): gives its first number: seat is 0. Now the inner range depends on the outer variable: range(row) gives 1 number on row 1, 2 on row 2, and so on.
  56. Line 13. runs += 1 changes runs from 0 to 1.
  57. Line 12. for seat in range(row): has no number left: a range stops before its stop value, 1, so the loop ends.
  58. Line 11. for row in range(1, 5): gives the next number: row is 2.
  59. Line 12. for seat in range(row): gives its first number: seat is 0.
  60. Line 13. runs += 1 changes runs from 1 to 2.
  61. Line 12. for seat in range(row): gives the next number: seat is 1.
  62. Line 13. runs += 1 changes runs from 2 to 3.
  63. Line 12. for seat in range(row): has no number left: a range stops before its stop value, 2, so the loop ends.
  64. Line 11. for row in range(1, 5): gives the next number: row is 3.
  65. Line 12. for seat in range(row): gives its first number: seat is 0.
  66. Line 13. runs += 1 changes runs from 3 to 4.
  67. Line 12. for seat in range(row): gives the next number: seat is 1.
  68. Line 13. runs += 1 changes runs from 4 to 5.
  69. Line 12. for seat in range(row): gives the next number: seat is 2.
  70. Line 13. runs += 1 changes runs from 5 to 6.
  71. Line 12. for seat in range(row): has no number left: a range stops before its stop value, 3, so the loop ends.
  72. Line 11. for row in range(1, 5): gives the next number: row is 4.
  73. Line 12. for seat in range(row): gives its first number: seat is 0.
  74. Line 13. runs += 1 changes runs from 6 to 7.
  75. Line 12. for seat in range(row): gives the next number: seat is 1.
  76. Line 13. runs += 1 changes runs from 7 to 8.
  77. Line 12. for seat in range(row): gives the next number: seat is 2.
  78. Line 13. runs += 1 changes runs from 8 to 9.
  79. Line 12. for seat in range(row): gives the next number: seat is 3.
  80. Line 13. runs += 1 changes runs from 9 to 10.
  81. Line 12. for seat in range(row): has no number left: a range stops before its stop value, 4, so the loop ends.
  82. Line 11. for row in range(1, 5): has no number left: a range stops before its stop value, 5, so the loop ends.
  83. Line 14. print("A triangle of 4 rows runs it", runs, "times: 1 + 2 + 3 + 4") prints A 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.

A grid of seats A1 to C4 numbered 1 to 12 in the order the inner block runs: all of row A first, then row B, then row C.row AA1run 1A2run 2A3run 3A4run 4row BB1run 5B2run 6B3run 7B4run 8row CC1run 9C2run 10C3run 11C4run 12

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

  1. Question 1 of 2 for i in range(4): has for j in range(6): inside it. How many times does the inner block run?

    Type a number.

    A hint

    The inner loop runs all its passes on every pass of the outer loop.

    Show the answer: Question 1 of 2

    Answer: 24 times

    The inner loop makes 6 passes on each of the outer loop's 4 passes, and it starts again from the beginning every time: 4 × 6 = 24.

  2. Question 2 of 2 for i in range(1, 11): has for j in range(i): inside it. How many times does the inner block run?

    Type a number.

    A hint

    The inner size changes from row to row. Add the sizes up.

    Show the answer: Question 2 of 2

    Answer: 55 times

    Row i has i passes, so the total is 1 + 2 + … + 10, which is 10 × 11 ÷ 2 = 55. The product rule does not apply, because the inner loop's size depends on the outer variable.

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:

An inner loop, and the same row as one string Python · stars_by_hand.py
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

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

  1. One question What does this print?

    Read the code, then choose one answer.

    i = 3
    print("-" * (4 - i) + "*" * i)
    Show the answer: One question

    Answer: -***

    "-" * 1 is "-" and "" 3 is "", and + joins them into one row, "-". Building the whole row first lets you print it, or check it, as one value.

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():

Pyramid, inverted pyramid and diamond Python · pyramids.py
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

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

  1. Question 1 of 2 A pyramid has n = 6 rows. How many stars are on row 5?

    Type a number.

    A hint

    Row i has 2 * i - 1 stars.

    Show the answer: Question 1 of 2

    Answer: 9 stars

    The stars go up by two per row, starting from 1, so row i has 2 × i − 1. Row 5 has 2 × 5 − 1 = 9 stars, after n − i = 1 space.

  2. Question 2 of 2 How many rows does the diamond of pyramids.py print for n = 4?

    Type a number.

    A hint

    The pyramid, then the inverted pyramid without its widest row.

    Show the answer: Question 2 of 2

    Answer: 7 rows

    The pyramid prints 4 rows and the second loop, range(n - 1, 0, -1), prints 3 more, so the widest row appears once: 4 + 3 = 7, which is 2 × n − 1.

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:

Floyd's and Pascal's triangles Python · number_triangles.py
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

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:

Interactive · line by line The next row of Pascal's triangle Step through the loop and watch next_row grow. Each number it adds is the sum of the two numbers above it in row.

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

After line 6: row is [1, 3, 3, 1]; next_row is [1, 4, 6, 4, 1]; k is 3.row10313213next_row1041624314k3
  • 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

[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.

Line run 6
Next line end
Loop pass –
Every step as text
  1. Start. No line has run yet, so there are no variables. Python starts with line 1.
  2. Line 1. row = [1, 3, 3, 1] makes row a list of 4 items.
  3. Line 2. next_row = [1] makes next_row a list of 1 item.
  4. Line 3. for k in range(1, len(row)): gives its first number: k is 1.
  5. Line 4. next_row.append(row[k - 1] + row[k]) adds 4 to the end of next_row. k is 1, so this adds row[0] + row[1], 1 + 3 = 4: the two numbers above the new one.
  6. Line 3. for k in range(1, len(row)): gives the next number: k is 2.
  7. Line 4. next_row.append(row[k - 1] + row[k]) adds 6 to the end of next_row.
  8. Line 3. for k in range(1, len(row)): gives the next number: k is 3.
  9. Line 4. next_row.append(row[k - 1] + row[k]) adds 4 to the end of next_row.
  10. 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.
  11. Line 5. next_row.append(1) adds 1 to the end of next_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.
  12. 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

  1. Question 1 of 2 Floyd's triangle of number_triangles.py is extended to a sixth row. What is the first number of row 6?

    Type a number.

    A hint

    The counter is never reset between rows.

    Show the answer: Question 1 of 2

    Answer: 16

    Row 5 ends with 15, and number is created before both loops, so it carries on counting: row 6 starts at 16 and holds 16 to 21.

  2. Question 2 of 2 Which row of Pascal's triangle comes after 1 4 6 4 1?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: 1 5 10 10 5 1

    A row begins and ends with 1, and each number in between is row[k - 1] + row[k]: 5, 10, 10 and 5. These are math.comb(5, k) for k from 0 to 5.

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.

A multiplication grid Python · times_grid.py
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

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.

Multiplication Table Generator Make a multiplication chart with rows and columns from 1 to 6 to check the grid this program prints.

Checkpoint

Check: Columns with rjust()

  1. One question times_grid.py is run with size = 12. How many characters wide is each cell?

    Type a number.

    A hint

    The width comes from the widest product, plus one space.

    Show the answer: One question

    Answer: 4 characters

    The widest product is 12 × 12 = 144, three digits, and one space separates the columns, so cell is 3 + 1 = 4 and every number is padded with rjust(4).

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:

Interactive · line by line A break that leaves only the inner loop Step through the search for the first row with two free seats side by side. X is taken and . is free; watch both flags.

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

After line 4: hall is ['XX.XX', 'X..XX', 'XXX..'] (the loop stopped at position 3); r is 2; row is 'XXX..'; s is 3.hall'XX.XX'0'X..XX'1'XXX..'23endr2row'XXX..'s3
  • 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

Found: 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.

Line run 4
Next line end
Loop pass 3
Every step as text
  1. Start. No line has run yet, so there are no variables. Python starts with line 1.
  2. Line 1. hall = ["XX.XX", "X..XX", "XXX.."] makes hall a list of 3 items.
  3. Line 4. for r, row in enumerate(hall): takes the item at position 0 of hall, numbered 0: r is 0 and row is 'XX.XX'.
  4. Line 5. for s in range(len(row) - 1): gives its first number: s is 0.
  5. Line 6. row[s] == "." and row[s + 1] == "." is false (row is 'XX.XX' and s is 0), so Python skips the block under if row[s] == "." and row[s + 1] == ".":.
  6. Line 5. for s in range(len(row) - 1): gives the next number: s is 1.
  7. Line 6. row[s] == "." and row[s + 1] == "." is false (row is 'XX.XX' and s is 1), so Python skips the block under if row[s] == "." and row[s + 1] == ".":.
  8. Line 5. for s in range(len(row) - 1): gives the next number: s is 2.
  9. Line 6. row[s] == "." and row[s + 1] == "." is false (row is 'XX.XX' and s is 2), so Python skips the block under if row[s] == "." and row[s + 1] == ".":.
  10. Line 5. for s in range(len(row) - 1): gives the next number: s is 3.
  11. Line 6. row[s] == "." and row[s + 1] == "." is false (row is 'XX.XX' and s is 3), so Python skips the block under if row[s] == "." and row[s + 1] == ".":.
  12. 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.
  13. Line 4. for r, row in enumerate(hall): takes the item at position 1 of hall, numbered 1: r is 1 and row is 'X..XX'.
  14. Line 5. for s in range(len(row) - 1): gives its first number: s is 0.
  15. Line 6. row[s] == "." and row[s + 1] == "." is false (row is 'X..XX' and s is 0), so Python skips the block under if row[s] == "." and row[s + 1] == ".":.
  16. Line 5. for s in range(len(row) - 1): gives the next number: s is 1.
  17. Line 6. row[s] == "." and row[s + 1] == "." is true (row is 'X..XX' and s is 1), so the block under if row[s] == "." and row[s + 1] == ".": runs.
  18. Line 7. print("Found: row", r, "seats", s, "and", s + 1) prints Found: row 1 seats 1 and 2.
  19. Line 8. break leaves the loop at once, without reading the items it has not reached. The bug This break leaves only the inner loop, the one over seats. The outer loop is still running, so it moves on to the next row.
  20. Line 4. for r, row in enumerate(hall): takes the item at position 2 of hall, numbered 2: r is 2 and row is 'XXX..'.
  21. Line 5. for s in range(len(row) - 1): gives its first number: s is 0.
  22. Line 6. row[s] == "." and row[s + 1] == "." is false (row is 'XXX..' and s is 0), so Python skips the block under if row[s] == "." and row[s + 1] == ".":.
  23. Line 5. for s in range(len(row) - 1): gives the next number: s is 1.
  24. Line 6. row[s] == "." and row[s + 1] == "." is false (row is 'XXX..' and s is 1), so Python skips the block under if row[s] == "." and row[s + 1] == ".":.
  25. Line 5. for s in range(len(row) - 1): gives the next number: s is 2.
  26. Line 6. row[s] == "." and row[s + 1] == "." is false (row is 'XXX..' and s is 2), so Python skips the block under if row[s] == "." and row[s + 1] == ".":.
  27. Line 5. for s in range(len(row) - 1): gives the next number: s is 3.
  28. Line 6. row[s] == "." and row[s + 1] == "." is true (row is 'XXX..' and s is 3), so the block under if row[s] == "." and row[s + 1] == ".": runs.
  29. Line 7. print("Found: row", r, "seats", s, "and", s + 1) prints Found: row 2 seats 3 and 4.
  30. Line 8. break leaves the loop at once, without reading the items it has not reached.
  31. Line 4. for r, row in enumerate(hall): finds no item at position 3 of hall (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:

Stopping both loops Python · free_seats_fixed.py
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

  • Return from a function. return ends the function at once, however deeply the loops are nested; returning None after 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 break there 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

  1. Question 1 of 2 Why does free_seats_break.py report two rows when only the first was wanted?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: break left the inner loop only, so the outer loop went on to the next row

    break leaves the innermost loop it is in. The search in row 1 stopped, but the loop over rows carried on, found a second pair in row 2 and reported it too.

  2. Question 2 of 2 You must stop a search in a grid at the first match and also know where it was. Which version does that most clearly?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Put the loops in a function and return the position from inside the inner loop

    A function that returns as soon as it finds the answer stops every loop it is in, and returning None after the loops says that nothing was found. A flag tested in the outer loop works too, with more lines.

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:

Making trailing spaces visible Python · hidden_spaces.py
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

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..

Text Diff Paste the pattern your program prints and the one you expected, then compare them by character to see every difference, spaces included.

Checkpoint

Check: Spaces at the end of a row

  1. One question What does this print?

    Read the code, then choose one answer.

    print(repr("*".center(3)))
    Show the answer: One question

    Answer: ' * '

    center(3) pads "*" to three characters, one space before and one after. print() alone would not show the space at the end; repr() writes the string with its quotes, so it does.

Python Online Compiler Try your own patterns in a full editor, in your browser.

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": n rows. Row i (counting from 1) has 2 * i - 1 stars, 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, so 2 * n - 1 rows.
  • "pascal": the first n rows 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 other kind raises ValueError: write raise 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 1

Starter 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.

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.

  1. Question 1 of 17 When does the inner loop of two nested loops start again from its first item?

    Choose one answer.

    Show the answer: Question 1 of 17

    Answer: On every pass of the outer loop

    The inner loop is a statement in the outer loop's body, so each outer pass runs it from the start: seat 1 again for row B, as the figure showed.

  2. Question 2 of 17 How many times does the inner block run? for i in range(5): with for j in range(3): inside it.

    Type a number.

    Show the answer: Question 2 of 17

    Answer: 15 times

    The inner loop runs all 3 of its passes on each of the 5 passes of the outer loop: 5 × 3 = 15.

  3. Question 3 of 17 And with for i in range(1, 6): outside and for j in range(i): inside?

    Type a number.

    Show the answer: Question 3 of 17

    Answer: 15 times

    The inner loop's size changes from row to row: 1 + 2 + 3 + 4 + 5 = 15, which is 5 × 6 ÷ 2. The same total as the first question, by a different route.

  4. Question 4 of 17 What does seat_labels.py print?

    Choose one answer.

    Show the answer: Question 4 of 17

    Answer: A1 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

    The outer loop picks a row and the inner loop labels all four of its seats before the next row starts, so each printed line is one row. The counter goes up once per inner pass: 12 for the hall, 10 for the triangle.

  5. Question 5 of 17 What is "*" * 4?

    Choose one answer.

    Show the answer: Question 5 of 17

    Answer: '****'

    String repetition gives one string with the copies side by side, which does the job of an inner loop that prints one star at a time.

  6. Question 6 of 17 What does this print?

    Read the code, then choose one answer.

    parts = []
    for n in range(1, 4):
        parts.append(str(n * n))
    print(", ".join(parts))
    Show the answer: Question 6 of 17

    Answer: 1, 4, 9

    Building the parts in a list and joining them makes one string for the whole row: "1, 4, 9". join() takes strings only, which is why each number goes through str() first.

  7. Question 7 of 17 Row i of a pyramid (counting from 1) has how many stars?

    Choose one answer.

    Show the answer: Question 7 of 17

    Answer: 2 * i - 1

    The rows have 1, 3, 5, 7 … stars: two more on each row, starting from 1, which is 2 * i - 1. n - i is the number of spaces in front of them.

  8. Question 8 of 17 A pyramid has n = 5 rows. How many spaces come before the stars of row 2?

    Type a number.

    Show the answer: Question 8 of 17

    Answer: 3 spaces

    Row i has n − i spaces in front, so row 2 of a 5-row pyramid has 5 − 2 = 3 spaces and then 2 × 2 − 1 = 3 stars.

  9. Question 9 of 17 With the same row formula, " " * (n - i) + "*" * (2 * i - 1), which loop prints the pyramid upside down?

    Choose one answer.

    Show the answer: Question 9 of 17

    Answer: for i in range(n, 0, -1)

    Changing only the order of i turns the pyramid over: range(n, 0, -1) gives n, n − 1 … 1. The stop value 0 is left out, so the last row is the one with a single star.

  10. Question 10 of 17 In Floyd's triangle, why is number = 1 written before both loops?

    Choose one answer.

    Show the answer: Question 10 of 17

    Answer: So it keeps counting from one row to the next

    A counter set inside the outer loop would start again on every row. Set once, before both loops, it numbers the whole triangle: 1, then 2 3, then 4 5 6.

  11. Question 11 of 17 What is the middle number of the row that comes after 1 5 10 10 5 1?

    Type a number.

    A hint

    Each inner number is the sum of the two numbers above it.

    Show the answer: Question 11 of 17

    Answer: 20

    The next row is 1 6 15 20 15 6 1, and its middle number is 10 + 10 = 20, the two numbers above it. It is also math.comb(6, 3), the ways to choose 3 items out of 6.

  12. Question 12 of 17 What does this print?

    Read the code, then choose one answer.

    print(repr("7".rjust(3)))
    Show the answer: Question 12 of 17

    Answer: ' 7'

    rjust(width) puts spaces in front of the string until it is width characters long, so numbers of different lengths end in the same column.

  13. Question 13 of 17 A report prints names of different lengths in a column 10 characters wide, lined up on the left, with the marks after them. Which call pads each name?

    Choose one answer.

    Show the answer: Question 13 of 17

    Answer: name.ljust(10)

    For left-aligned text, pad on the right with ljust(width). The padding makes every name the same width, so whatever comes after them starts in the same column.

  14. Question 14 of 17 A break inside the inner loop of two nested for loops runs. Where does the program carry on?

    Choose one answer.

    Show the answer: Question 14 of 17

    Answer: The outer loop goes on with its next item

    break leaves only the loop it is written in. To stop both, put the loops in a function and return, or set a flag and break the outer loop too, as in free_seats_fixed.py.

  15. Question 15 of 17 What does first_pair(["XXX", "X.X"]) of free_seats_fixed.py return?

    Choose one answer.

    Show the answer: Question 15 of 17

    Answer: None

    The return inside the loops runs only when a pair is found. When none is, the loops finish and return None says that nothing was found.

  16. Question 16 of 17 Which method removes the spaces at the end of a row, and only there?

    Choose one answer.

    Show the answer: Question 16 of 17

    Answer: rstrip()

    A pattern needs its left padding and no trailing spaces, so rstrip() is the one to use. Building rows with left padding only avoids the problem in the first place.

  17. Question 17 of 17 What does this print?

    Read the code, then choose one answer.

    for j in range(1, 3):
        print(j, end=" ")
    print("|")
    Show the answer: Question 17 of 17

    Answer: 1 2 |

    Each print(j, end=" ") writes the number and a space instead of a new line, so the row ends with a space before the bar. Joining the numbers with " ".join() avoids that extra space.

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.

  1. 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.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. 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.

    Model answer, Pro. First step and follow-ups

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 i as formulas such as n - i and 2 * 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() and center() align text; center() and end=" " leave spaces at the ends of rows.
  • break leaves 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

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.