Loops and accumulation
Write a small program that transforms data using conditions, loops and functions.
THE IDEA
Doing something once per item
A for loop visits the items of a sequence one at a time. On each pass the loop variable is bound to the next item and the indented body runs once. You write the body one time; Python repeats it.
The most useful pattern is the accumulator: a name you set up before the loop and update inside it, so information carries from one pass to the next. A total starts at 0, a biggest-so-far starts at the first item.
nums = [3, 8, 1, 9]total = 0for n in nums: total = total + nBefore the loop: total is set to 0.
| pass | n | total after |
|---|---|---|
| start | - | 0 |
range: counting without writing the numbers out
range(n) produces 0, 1, ..., n-1: n values starting at zero. range(a, b) starts at a and stops before b, and a third number sets the step. As with slices, the stop value is never included.
range(0, 4) produces 4 values
One argument means range(stop) starting from 0. Try start 1, stop 6 and then step 2, then start 5, stop 0, step -1.
Predict first. What is the sum of the values produced by range(4)?
while: repeat until a condition fails
When you do not know in advance how many passes you need, use while condition:. The body repeats as long as the condition is true, so the body must change something that the condition looks at. Otherwise the loop never ends.
value = 100
steps = 0
while value > 1:
value = value // 2 # 50, 25, 12, 6, 3, 1
steps = steps + 1
print(steps) # 6The classic mistake: resetting the accumulator
total = 0
for n in [3, 8, 1, 9]:
total = 0 # reset on every pass!
total = total + n
print(total) # 9, not 21: only the last item survivesSet the accumulator up above the loop. Inside the loop it should only be updated. The trace above shows the correct version: the "total after" column keeps growing.
Chapter context
A program is a precise sequence of state changes. Python names refer to objects; reading a program means tracking the values those names refer to, rather than guessing from how the code sounds.
TRY IT YOURSELF
Exercise 1: an accumulator loop
- Write one
forloop overnumbers. Each pass adds the number tototal, adds 1 tocountand updatesbiggestwhen the number is larger. - After the loop, set
meantototal / count. Your program is re-run on other lists, including one with only negative numbers.
Exercise 2: range and while
range(1, 6)gives 1, 2, 3, 4, 5. The stop value is never included.- Fill
multipleswith the first five multiples ofnusing aforloop over a range andappend. - Then use a
whileloop that halvesvaluewith//until it is no longer greater than 1, counting the halvings insteps.
Both exercises must be solved to finish this lesson.
Stuck, or something not working? You can come back to it any time.
CHECK YOUR UNDERSTANDING
Sum the values emitted by range(4).
Chapter reference: math, worked example & code
This section belongs to the whole chapter, so it is the same on every lesson in it and may cover a different lesson's topic. The code for the experiment you just ran is inside the experiment itself.
Math and notation
For an accumulator over numbers :
The subscript denotes a step, not a Python index. After the last step, is the sum. For a mean, divide by the number of items, and define what should happen for an empty list.
Worked example
Trace a robot's forward distances [2, 1, 3]. Position starts at zero and changes to 2, then 3, then 6. Replacing three copy-pasted moves with a loop preserves the order and final state. A mean distance is 6/3 = 2; the count is 3, not the last list index 2.
Reference code
The following example uses the Python standard library and does not call a remote service.
moves = [2, 1, 3]
position = 0
for distance in moves:
position += distance
assert position == 6
assert sum(moves) / len(moves) == 2
Python examples are provided for study and local execution; this page does not execute Python.
Common mistakes
Assignment does not copy a mutable object. A loop stop value is exclusive. A function can return None even when its print output looks correct.