1.Why should I care?
A function gives a calculation a name, a clear list of inputs and one output. Write it once, check it once, and every part of the program that calls it gets the same correct answer. That is how large engineering programs stay trustworthy.
- ◇ Define a function with parameters and a return value, and call it with arguments.
- ◇ Explain the difference between returning a value and printing it.
- ◇ Write a docstring that states what the function does and the units of its inputs and output.
2.Discover
Choose wheel_speed_m_per_s. Feed it 60 rpm and 0.1 m and work out the answer by hand first. Then compare versions A, B and C: which one matches your hand calculation? Run the tests to confirm.
Loading the interactive…
Can't use the interactive? Read a description instead
The function machine shows a Python function with a docstring, three versions of its body and a set of assert tests. For wheel_speed_m_per_s: version A (rpm / 60 * math.pi * diameter_m) passes all three tests; version B forgets to divide by 60 (60 rpm, 0.1 m gives 18.85 instead of 0.314 m/s); version C uses 2π with the diameter (0.628 m/s).
3.Checkpoint: guided practice
Check what you just discovered before going on. Hints appear after a wrong answer.
Practice 1 · a fresh version every time
def wheel_speed_m_per_s(rpm, diameter_m): return rpm / 60 * math.pi * diameter_m. What does wheel_speed_m_per_s(150, 0.05) return, in m/s?
Practice 2
Why is return better than print inside a calculation function?
4.Apply it
Write rpm_for_speed(speed_m_per_s, diameter_m), the inverse of wheel_speed_m_per_s, with a docstring. Check that wheel_speed_m_per_s(rpm_for_speed(0.5, 0.065), 0.065) gives 0.5 (within a tolerance).
5.Understand
Define once, call many times
import math
def wheel_speed_m_per_s(rpm, diameter_m):
"""Ground speed of a wheel in m/s, from its rpm and diameter in metres."""
return rpm / 60 * math.pi * diameter_m
print(round(wheel_speed_m_per_s(120, 0.065), 3)) # 0.408def names the function, the brackets list its parameters, and return hands back the result.
Return, don't just print
A returned value can be stored, compared, tested or passed to another function: if wheel_speed_m_per_s(rpm, d) > 1.5: slow_down(). Printing inside a function only shows text and gives back None. Keep functions quiet; print at the top level of the program.
A docstring is a promise
The triple-quoted line under def is a docstring. It says what the function does and the units of its inputs and output. Anyone using the function should be able to trust it without reading the body, and tests (next lesson) check that the promise is kept.
Explain it another way
A function is a machine: put the inputs in the hopper, it does the same job every time, and one answer comes out of the chute.
Calling a function binds each parameter to an argument in a new local scope, runs the body, and evaluates to the returned object (None if there is no return). Local variables disappear when the call ends.
v = (n/60)·π·d: n/60 turns per second times the circumference π·d metres per turn. Units: (1/s) × m = m/s. 120 rpm with a 65 mm wheel gives 2 × π × 0.065 ≈ 0.408 m/s.
Robot firmware has functions like this for every conversion (encoder ticks to metres, ADC counts to volts). A unit-conversion fix in one function reaches everywhere at once.
Worked example 1
Write mean(values) that returns the mean of a non-empty list, and use it for [41.2, 42.0, 43.5].
def mean(values): / """Mean of a non-empty list of numbers.""" / return sum(values) / len(values). Then mean([41.2, 42.0, 43.5]) returns about 42.23. The docstring states the condition 'non-empty', which the caller must respect.
Common mix-ups
- A function that prints its answer has returned it.
✓ Printing shows text; only return gives the caller a value. - Parameters must have the same names as the variables you pass in.
✓ Arguments are matched by position (or by name=value). The names inside and outside can differ.
6.Watch
→ Watch the difference between printing inside a function and returning a value, and how arguments fill the parameters.
Defining functions with parameters and return values, so one calculation can be reused and tested.
Length: see YouTube · captions on YouTube · source
Nothing loads from YouTube until you press play.
The video is optional: everything you need is also in the lesson text and the interactive.
7.Practice on your own
Practice, not a test. Wrong answers get a hint and another try.
Practice 3
def area_m2(width_m, height_m): return width_m * height_m. What does area_m2(3, 0.5) return?
Practice 4
def f(x): x * 2 (no return). What does f(4) give?
Practice 5
Using v = rpm / 60 × π × d, what speed in m/s does a 0.2 m wheel at 30 rpm give, to 3 decimal places?
8.Predict
def double(x): print(x * 2). What is stored in y after y = double(5)?
Guess first. Being wrong here is how the surprise works.
9.Reflect
10.Go further
- Python tutorial: defining functions ↗The official guide to def, parameters, return and docstrings.
Concepts: Functions and decomposition