Python Nested Loops
A nested loop is a loop placed inside another loop. The outer loop moves from row to row.
A loop inside a loop
The inner loop runs three times. Then the outer loop moves on.
for row in range(2):
for marker in range(3):
print(row, marker)Build one row at a time
The inner loop adds one star at a time. The print runs after the inner loop ends.
for row in range(3):
line = ""
for col in range(4):
line += "*"
print(line)Count every round
Three outer rounds meet four inner rounds. That makes twelve rounds in total.
rounds = 0
for row in range(3):
for col in range(4):
rounds += 1
print(rounds)Example
for row in range(1, 5):
line = ""
for col in range(1, 6):
if col > 1:
line += " "
line += str(row * col)
print(line)Key points
- Nested loop: a loop that sits inside another loop
- Use the outer loop to move from row to row
- Use the inner loop to handle one row at a time
- Total rounds: outer rounds multiplied by inner rounds
In this example, row takes the values 1 to 4. For each row, line starts as an empty string. The inner loop runs with col from 1 to 5. A space is added before every value after the first. Each product is turned into text and added to line. The finished line prints after the inner loop ends. Four rows print, and each row holds five products.
Note
In Python, build each new row inside the outer loop.
A row built outside it keeps growing on every row.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
A loop runs 3 outer rounds. Its inner loop runs 5 rounds each time. How many times does a print inside the inner loop run?