Functions and a robot
Write a small program that transforms data using conditions, loops and functions.
THE IDEA
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.
def average(nums): total = 0 for n in nums: total = total + n return total / len(nums) result = average([2, 1, 3]) + 1result = 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.
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) + 1The 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'
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.
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
Part 1: functions that return
- A function that only prints cannot be used by other code: its result is the special value
None. Make each functionreturnits answer. areacurrently prints.averageanddescribeare empty. Every function is called several times with different inputs.
Mission 1: walk(n)
The robot stands at the left edge of a corridor, facing east. The flag is 5 squares ahead. Write the function walk(n), then use it.
The program made no moves.
Mission 2: turn_around() and back again
Walk to the flag, come back to where you started, and end up facing east again. You will need turn_around(), a function that calls other functions.
The program made no moves.
Mission 3: climb the staircase
Walls form a staircase. The robot cannot walk through walls (a crash stops the program). Package one stair as a function, then repeat it with a loop to reach the flag at the top.
The program made no moves.
Solve the function exercise and all three robot missions to finish this lesson.
Stuck, or something not working? You can come back to it any time.
CHECK YOUR UNDERSTANDING
For def twice(x): return 2*x, evaluate twice(3) + 1.
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.