Lesson 9 of 10
A loop can contain another loop. The inner loop runs completely, from start to finish, for every single pass of the outer loop.
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
The outer loop runs 3 times; the inner runs 3 times for each of those — so the body executes 9 times total. That multiplication is the thing to keep in mind: an outer loop of 100 around an inner loop of 100 is ten thousand iterations.
Building rows
Nested loops shine when your data has rows and columns. Here the outer loop handles each row, and the inner loop builds that row's content.
for row in range(1, 4):
line = ""
for star in range(row):
line += "*"
print(line)
That draws a small triangle. Notice line is reset at the top of each outer pass — that is what
makes each row start fresh.
A multiplication table
for i in range(1, 4):
row = ""
for j in range(1, 4):
row += f"{i * j} "
print(row.strip())
.strip() removes the trailing space that the accumulator leaves behind.
break only escapes one level
This surprises people: break exits the loop it is directly inside, not all of them.
for i in range(1, 4):
for j in range(1, 4):
if j == 2:
break
print(i, j)
The break ends the inner loop each time, but the outer loop keeps right on going.
Try it yourself
Use nested loops to print a three-row triangle of stars.
Checkpoint
- The inner loop completes fully on every pass of the outer loop.
- Total iterations multiply — outer times inner.
breakexits only the loop it sits directly inside.- Reset any per-row variable at the top of the outer loop.
Questions about this lesson
Log in to ask a question.