LearnWave
Learn it. Master it.

Flow of Control

Nested loops

Print a pattern with nested loops.

A loop inside another loop is a nested loop. Python puts no limit on how deeply loops can be nested, and for and while loops can be nested inside each other in any combination.

For each single iteration of the outer loop, the inner loop runs completely, from start to finish. With an outer loop of 2 turns and an inner loop of 3 turns, the inner body runs 2 × 3 = 6 times in all.

Nested loops are useful for working in rows and columns, such as printing patterns. For example, an outer loop for i in range(1, 5) makes the rows. Inside it, an inner loop for j in range(1, i + 1) prints '#' with end=' ', so row i gets i symbols. After the inner loop, an empty print() starts a new line. The output is a triangle of 4 rows: one # in the first row, two in the second, and so on.

The book has more examples:

  • Program 6-18 finds the prime numbers from 2 to 49: for each number, an inner while loop tries divisors; if none divides it, the number is prime.
  • Program 6-19 puts a for loop inside an if..else block to find a factorial (5! = 5 × 4 × 3 × 2 × 1 = 120), with separate messages for negative numbers and for 0.
Inner loop runs fully for each outer turn.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.