Set up
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.
Run python loop.py and line 1 runs first: total = 0. total will hold the running sum, so it starts at zero. It must exist before the loop, because line 3 reads it.
Three passes
Line 2 is a for statement. [1, 2, 3] is a list: several values in order, inside square brackets. On the first pass, for takes the first item, 1, and stores it in the loop variable n.
Line 3 is indented, so it is the loop's body: the lines that repeat. Python reads total (0) and n (1), adds them, and stores the answer, 1, back in total.
The body has no more lines, so Python jumps back up to line 2 for the next item. n now holds 2: the new value replaces the old one. One run through the body is called an iteration.
The same line 3 runs again, now with new values: 1 + 2 is 3. You wrote the addition once, and the loop reuses it for every item.
Back to line 2 once more. The last item, 3, goes into n. A for loop visits every item exactly once, in order, never skipping one or taking one twice.
Line 3 runs a third time: 3 + 3 is 6. total now holds the sum of the whole list, 1 + 2 + 3.
After the loop
Back at line 2 there are no items left, so the loop ends. Line 4 is not indented, so it is outside the loop and runs only once: print(total) shows 6.
You rarely type the numbers out. range(1, 4) counts 1, 2, 3: it starts at 1 and stops just before 4. Put it on line 2 and the loop makes the same three passes and prints 6 again.
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).