[0]1[1]2[2]31total = 02for n in [1, 2, 3]:for n in range(1, 4):3 total = total + n4print(total)010 + 121 + 233 + 36
Code card: loop.py; the highlighted line is the one runningThe list: three items the loop visits in orderTerminal: where print() writesMemory boxes: the values stored under n and totalA for loop runs its indented body once for each item of a list. loop.py adds up 1, 2 and 3. Each step lights the parts it is about. A value token hops along the step's arrow: 0 into total, each item into n, the sum back into total, and at the end 6 to the terminal. The loop-back arrow lights each time Python jumps from the body back up to the for line. In the last step line 2 becomes for n in range(1, 4):: the same three items, the same three passes.

Set up

  1. A loop runs the same lines again and again. Python has two kinds: a for loop repeats once for each item in a sequence; a while loop repeats as long as a condition is True. Here a for loop adds up a list.

Three passes

After the loop

Try it yourself

;; step 1/10
# without a loop: one line per number
total = 0
total = total + 1
total = total + 2
total = total + 3

# with a loop: the addition is written once
for n in [1, 2, 3]:
    total = total + n

Python's style guide, PEP 8, uses four spaces for each level of indentation. Every line of a loop's body must be indented by the same amount; the first line that is not indented is outside the loop. A while loop checks its condition before every pass. If nothing in the body ever makes the condition False, the loop never ends; press Ctrl-C to stop the program (Python raises KeyboardInterrupt).