← Python lessons

Nested Loops & Ifs

A nested loop is a loop inside another loop. Each time execution reaches the inner loop, it starts a new traversal. In the examples here, that traversal finishes before the outer loop moves to its next item.

Every combination

for size in ["S", "M"]:
    for colour in ["red", "blue"]:
        print(size, colour)

The output is:

S red
S blue
M red
M blue

The outer loop takes two turns. On each one, the inner loop takes two turns of its own — so four lines are printed. Indentation is what puts the inner loop inside the outer one.

A separate count for each group

for threshold in [3, 6]:
    count = 0
    for score in [2, 4, 7]:
        if score >= threshold:
            count = count + 1
    print(threshold, count)

The output is:

3 2
6 1

For each threshold, the inner loop visits all three scores. count = 0 is inside the outer loop, so each threshold starts with a fresh count. The final print is inside the outer loop but after the inner loop: it runs once per threshold.

If the count were initialized before the outer loop, the second threshold would inherit the first threshold's count. Put initialization at the level where a new result should begin.

See also: For loops, The range() function, Modulo and divisibility.

Trace the traversal

Before running the size/colour example, list the pairs in order. If the outer list has 3 items and the inner list has 2, how many lines will be printed? Explain which loop starts a new traversal for each outer item.

An if inside an if

Nested control structures can be decisions as well as loops.

is_member = True
age = 14
if is_member:
    if age < 16:
        print("Junior member")
    else:
        print("Adult member")
else:
    print("Visitor")

The outer decision checks membership. Only members reach the inner age decision. Indentation shows which if each else belongs to. Here the result is Junior member; a non-member prints Visitor regardless of age.

An if inside a loop checks a condition on each iteration, as in the score-counting example above. A loop inside an if runs only when that decision permits it.

Your turn: nest decisions

Use an outer if for membership and an inner if for age. Print Junior member for members under 16, Adult member for older members, and Visitor for non-members.

is_member = True
age = 17
# Add the nested decisions.

Expected output

Adult member

See also: if, elif, else, Tracing Code.


Practise this in the free Python course, where every exercise checks your code instantly.