Nested loops

Loops, lesson 5 of 5

🔁 Loops, lesson 5 of 5

Nested loops

Put a loop inside a loop to handle rows, columns and combinations.

10 min

1 exercise

2 quizzes

0/3 solved

Getting Python ready… examples can run in a moment.

A loop can live inside another loop. For each pass of the outer loop, the inner loop runs all the way through. Think rows and columns: the outer loop picks a row, the inner loop walks across it.

Example

Multiplication grid

:4 pads each number to 4 characters so the columns line up. Try a 9 × 9 grid.

Example

Outfit combinations

Add a third shirt. How many outfits now?

Quiz

What does this print?

Example

Draw a staircase

The empty print() ends each row. (Shortcut: the whole inner loop could be print("#" * i).)

Example

Find a free seat

Remove the outer if found: break and see how many seats get printed.

Quiz

What does this print?

Exercise

Number staircase

Use nested loops to print this staircase, one row per line (size rows):

1
12
123
1234