1total = 02for n in range(1, 5):3 total = total + n4print(total)5while total > 4:6 total = total - 37while True:8 breakout∞51234
Code card: the highlighted line is running; curved arrows show where each loop jumps backMemory boxes: total and n, showing their current valuesrange(1, 5): the numbers the for loop hands to n, one per passScreen: what print() showsEach step runs a few small moves. The highlight jumps between a loop's header and its body, and a value token hops along the step's arrow: from range into n, from the body's line into total, from total to a condition, or from total to the screen. The boxes' values crossfade when the token lands. The for loop takes 1, 2, 3 and 4 from range(1, 5), never 5, so total ends at 1 + 2 + 3 + 4 = 10. The while loop runs while total > 4 is True: 10, then 7, then 4, when it turns False. while True would never stop on its own; break ends it at once.

for loops

  1. Line 1 stores 0 in total. total will hold a running sum, so it must start at zero before the loop begins adding to it.

while loops

Forever and break

Try it in the Python prompt

;; step 1/10 · line 1: total = 0
>>> total = 0
>>> total
0

range(start, stop) counts up from start and stops just before stop, so range(1, 4) gives 1, 2, 3 and range(1, 5) gives 1, 2, 3, 4. range(5) on its own starts at 0: 0, 1, 2, 3, 4. Python knows which lines are the loop body from the indentation: the lines under the header that are indented further. The header line ends with a colon.