Foundations: Python, Git and toolsLoading progress…

Loops and accumulation

Write a small program that transforms data using conditions, loops and functions.

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.

Pass 1 of 5
nums = [3, 8, 1, 9]total = 0for n in nums: total = total + n

Before the loop: total is set to 0.

passntotal after
start-0
Pick a program, edit the numbers, and press the arrows to go pass by pass. The table keeps the history.

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

01234 (stop, not included)

One argument means range(stop) starting from 0. Try start 1, stop 6 and then step 2, then start 5, stop 0, step -1.

Change start, stop and step. The dashed chip is the stop value, which is never produced.

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)               # 6

The 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 survives

Set 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.

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 x1,…,xnx_1,\ldots,x_n:

s0=0,si=si−1+xi.s_0=0,\qquad s_i=s_{i-1}+x_i.

The subscript denotes a step, not a Python index. After the last step, sns_n 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.