Foundations: Python, Git and toolsLoading progress…

Functions and a robot

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

A function packages a computation

When you find yourself writing the same few lines again, wrap them in a function. def names it and lists its parameters (the inputs). Calling it with an argument runs the body with the parameters bound to those values. The body can make its own local names, which vanish when the call ends. return hands a value back to whoever called.

Moment 1 of 8
def average(nums): total = 0 for n in nums: total = total + n return total / len(nums) result = average([2, 1, 3]) + 1
inside average (local names)not entered yet
the callerresult = average([2, 1, 3]) + 1 (waiting for average to finish)

Python reaches the call. It pauses the line it was evaluating and jumps into the function, taking the argument with it.

Step through one call of average([2, 1, 3]). Left: the code. Top right: the function's local names. Bottom right: what the caller sees.

Returning is not printing

print shows text on the screen for a human. return gives a value to other code. A function with no return gives back None even if it printed something that looked right.

def twice(x): print(2 * x) y = twice(3) + 1

The screen shows 6, so it looks right.

But twice(3) hands back None, so the last line fails:

TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

The same function written two ways. Only one can be used inside a bigger expression.

Predict first. For def twice(x): return 2 * x, what is twice(3) + 1?

Predict first. For def f(x): x * 2 (no return), what does print(f(2)) show?

Functions that call functions: a robot

Functions really pay off when they build on each other. In the practice you control a small robot on a grid. Python gives you three tiny built-in actions, step() (move one square forward), turn_left() and turn_right(). You write bigger actions from them: walk(n) from step(), then turn_around(), then a whole stair(). The program you write records a list of actions and the grid replays them so you can see exactly what happened.

def walk(n):
    for _ in range(n):
        step()

walk(3)
turn_left()
walk(2)

6 actions recorded. Press Play or Next action.

The robot starts at the bottom left facing east. This program walks 3, turns left, then walks 2. Press Play, or go action by action.
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.