3.2.2 - Nested selection and iteration (Python)
A control structure can contain another structure. You will use indentation to identify which condition or counter controls each statement and trace nested Python decisions and loops.
Selection within selection
Nested selection makes an inner decision only when execution reaches it through an outer decision.
game_won = True
score = 18
high_score = 20
if game_won:
print("Winner")
if score > high_score:
print("New record")
else:
print("No new record")
else:
print("Try again")
The outer condition is true, so Winner is displayed. The inner comparison is false, so No new record follows. If game_won is false, the score comparison is never reached: only Try again appears. The inner else belongs to the inner if because their indentation matches. The outer else aligns with the outer if.
Separate decisions at the same indentation would behave differently. They could check a high score even after a loss. When tracing, evaluate only conditions on the selected execution path; do not run every branch on the page.
Iteration within iteration
A nested loop completes its inner repetitions for each execution of the outer body.
for row in range(1, 3):
for seat in range(1, 4):
print(row, seat)
The outer range contains rows 1 and 2. For row 1, the inner range produces seats 1, 2, 3; it starts afresh for row 2. The displayed pairs are (1,1), (1,2), (1,3), (2,1), (2,2), (2,3). There are 2 × 3 body executions, not 2 + 3. A statement after the inner loop but still inside the outer loop would run once per row.
The two loops need not have the same kind of control. Here a start-tested while controls the sessions and a count-controlled for controls two rounds within each session:
Rounds inside sessions
{"code":"session = 1\nwhile session <= 2:\n for round_number in range(1, 3):\n print(session, round_number)\n session = session + 1","instructions":"Predict the ordered pairs and run. Change the inner range stop from3 to 4 and run again. Explain why each session gains one round."}
The session update is inside the outer body but outside the inner body. It occurs after both rounds; placing it inside the inner loop would change the session number partway through those rounds. The outer condition controls whether another complete session begins. The inner range controls only the rounds of the current session.
Trace from the outside inward. An inner loop restarts whenever the outer body reaches it; indentation identifies the body of each control structure.