Nested Loops & Ifs
A nested loop is a loop inside another loop, and a nested if is an if inside another block. The inner block runs each time the outer one reaches it.
Every combination
for size in ["S", "M"]: for colour in ["red", "blue"]: print(size, colour)This prints 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 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)This prints 3 2, then 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 last
print is after the inner loop, so it runs once per threshold.
Set a starting value at the level where a new result should begin. If
count = 0 were above the outer loop, the second threshold would keep
adding to the first threshold's count.
An if inside an if
You can nest decisions too. The inner if runs only when the outer one is true.
is_member = Trueage = 14if is_member: if age < 16: print("Junior member") else: print("Adult member")else: print("Visitor")This prints Junior member. Indentation shows which if each else belongs
to. A non-member prints Visitor, whatever their age.
See also: For loops, The range() function, if, elif, else, Tracing Code.
Your turn
Use one loop inside another and an if to print every pair a b that adds up to 4.
1 3 2 2 3 1
for a in [1, 2, 3]: # add an inner loop over [1, 2, 3] and print a, b when a + b == 4 passAdvanced reading
- Pairs without repeats — start the inner loop after the outer item, and use
itertools. - Leaving nested loops early — why
breakonly stops the inner loop, and how to stop both.