Module 3

Nested repetition, introductory

A loop inside a loop.

Loops within loops

You can put a loop inside another loop. This is called a nested loop. The inner loop runs completely for each iteration of the outer loop.

Python
for i in range(3):
    for j in range(2):
        print(i, j)
0 0 0 1 1 0 1 1 2 0 2 1

For each value of i, the inner loop runs through all values of j. This produces every combination.

Try it

Nested loops are powerful but can be hard to follow. Start with simple examples and build up gradually.