Pylerno
English

Nested loops

Generate a table and calculate how many iterations it requires.

On this page

The concept

An inner loop runs for every iteration of its outer loop. A table with three rows and three columns therefore computes nine cells. If both dimensions grow with n, the work grows approximately as n squared. This does not make all nested loops wrong; it makes the size of the input important.

Output layout has its own control flow. The inner print uses an empty end string to remain on the row. A print after the inner loop starts the next line. Moving that call into or outside the wrong block changes the entire table layout.

Worked example

python
for row in range(1, 4):
    for column in range(1, 4):
        print(f"{row * column:3}", end="")
    print()
for stars in range(1, 5):
    print("*" * stars)

Trace the result

  1. The outer loop selects a row multiplier.
  2. The inner loop walks through all three column multipliers for that row.
  3. A newline is printed after each completed row; a separate loop then displays a triangle using string repetition.
text
  1  2  3
  2  4  6
  3  6  9
*
**
***
****
Line-by-line walkthrough

Lines 1–4: for row in range(1, 4):

Obtain each item from range(1, 4) and bind it to row before executing the body. A tuple-shaped target unpacks that item. A loop else, if present, runs only when completion does not use break.

Lines 2–3: for column in range(1, 4):

Obtain each item from range(1, 4) and bind it to column before executing the body. A tuple-shaped target unpacks that item. A loop else, if present, runs only when completion does not use break.

Line 3: print(f"{row * column:3}", end="")

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Line 4: print()

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Lines 5–6: for stars in range(1, 5):

Obtain each item from range(1, 5) and bind it to stars before executing the body. A tuple-shaped target unpacks that item. A loop else, if present, runs only when completion does not use break.

Line 6: print("*" * stars)

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Common mistake

A misplaced indentation level can turn a table into a column or a single long line. Trace both loop variables on paper.

Check your understanding

What does this program print?

python
count = 0
for row in range(2):
    for col in range(3):
        count += 1
print(count)
Choose one answer

Search documentation

Share this page