Writing and testing functions
Design functions with clear inputs and outputs, document them with docstrings, and prove they work with small assert-based tests — before a bug reaches the robot.
Lesson 4 of 6 · 35 min · Self-paced · Free
Why test a function?
Imagine a function that converts wheel encoder ticks into distance. Your robot's odometry, its speed estimate and its "stop after one metre" behaviour all call it. If it contains a small mistake, every one of those features is wrong — and nothing crashes, so nobody notices until the robot drives into a table leg. Functions let you write a calculation once; tests let you trust it once.
In the previous lesson on decisions and loops you learned to define functions with def, parameters and return. This lesson is about writing them well: giving each one a clear job, documenting it, and checking it automatically.
Return values, not just printing
A function can show something on screen with print, or hand a value back with return. They are not the same:
def show_speed(rpm):
print(f"Speed: {rpm} rpm")
result = show_speed(120)
print(result)Output:
Speed: 120 rpm
Noneshow_speed printed a message, but it returned nothing, which Python represents as the special value None. Any later code that tries to calculate with result will fail. A good rule: calculation functions return values; only the outer part of the program prints them. A function that just returns a value, without printing or changing anything else, is also the easiest kind to test.
Parameters with defaults
Many engineering functions have settings that rarely change. Give those parameters default values, so callers only supply them when they differ:
def adc_to_volts(counts, vref=3.3, max_count=1023):
"""Convert a raw analog-to-digital converter reading to volts.
counts: the integer reading, from 0 to max_count.
vref: the reference voltage in volts, which gives max_count.
max_count: the largest reading the converter can produce.
Returns the voltage as a float.
"""
return counts * vref / max_count
print(adc_to_volts(1023))
print(f"{adc_to_volts(2048, vref=5.0, max_count=4095):.3f}")Output:
3.3
2.501The second call names its arguments (vref=5.0). These keyword arguments make calls self-explanatory: a reader does not have to remember which number is which.
Docstrings: the contract
The triple-quoted text at the top of adc_to_volts is its docstring. A good docstring is a contract between the function and anyone who uses it. It says:
- what the function does, in one line;
- what each parameter means, including its units;
- what it returns;
- anything surprising, such as values it cannot handle.
Python stores the docstring with the function, so help(adc_to_volts) displays it. Writing it first is also a design test: if you cannot describe a function's job in one sentence, it is probably doing too much and should be split.
Returning more than one value
Sometimes a calculation naturally produces two results. Return them separated by commas and unpack them at the call:
def min_max(values):
"""Return the smallest and largest of a non-empty list of numbers."""
return min(values), max(values)
low, high = min_max([12.1, 12.4, 11.9, 12.6])
print(low, high)
print(f"Spread: {high - low:.1f}")Output:
11.9 12.6
Spread: 0.7Testing with assert
An assert statement checks that something is true. If it is, nothing happens. If it is not, the program stops with an AssertionError. That makes it a tiny, automatic test.
Here is a distance function for a wheel with an encoder. One full revolution of a wheel of diameter d rolls a distance of π × d, so a 65 mm wheel travels π × 65 ≈ 204.2 mm per revolution.
import math
def wheel_distance_mm(ticks, ticks_per_rev, diameter_mm):
"""Distance rolled by a wheel, in mm, from encoder ticks.
Negative ticks mean the wheel turned backwards.
"""
revolutions = ticks / ticks_per_rev
return revolutions * math.pi * diameter_mm
def test_wheel_distance():
# No ticks: no distance.
assert wheel_distance_mm(0, 360, 65) == 0
# One revolution: one circumference, worked out by hand.
assert math.isclose(wheel_distance_mm(360, 360, 65), 204.2035, rel_tol=1e-6)
# Half a revolution: half the distance.
assert math.isclose(wheel_distance_mm(180, 360, 65), 0.5 * math.pi * 65)
# Backwards: same size, opposite sign.
assert math.isclose(wheel_distance_mm(-360, 360, 65), -math.pi * 65)
test_wheel_distance()
print("wheel_distance_mm: all tests passed")Output:
wheel_distance_mm: all tests passedNotice three habits. Each test has a comment saying why the expected answer is right. Results that involve π are compared with math.isclose, never ==, because floats are approximate (rel_tol=1e-6 allows a relative difference of one part in a million, which covers rounding the hand-worked value to 204.2035). And the tests are gathered in a function whose name starts with test_, so they can be rerun after every change.
A test that catches a bug
Here is a clamp function, used to keep a speed command inside safe limits. It contains a realistic copy-and-paste mistake:
def clamp(value, low, high):
"""Limit value to the range low to high."""
if value < low:
return low
if value > high:
return low # bug: should be high
return value
def test_clamp():
assert clamp(50, 0, 100) == 50, "inside the range"
assert clamp(-20, 0, 100) == 0, "below the range"
assert clamp(150, 0, 100) == 100, "above the range"
assert clamp(0, 0, 100) == 0, "exactly on the lower edge"
assert clamp(100, 0, 100) == 100, "exactly on the upper edge"
try:
test_clamp()
print("clamp: all tests passed")
except AssertionError as error:
print("clamp: test FAILED:", error)Output:
clamp: test FAILED: above the rangeThe text after the comma in each assert is a message shown when it fails, so the failure tells you immediately which case broke. (The try/except lines catch the error so we can print it neatly; the lesson on errors explains them. Without them you would see a full traceback ending in AssertionError: above the range.) Change return low to return high and the same tests print clamp: all tests passed.
Imagine this bug in a robot: any speed request above the limit would be replaced by the minimum, perhaps full reverse. A five-line test found it in a second.
Choosing good test cases
A handful of well-chosen cases beats dozens of random ones. For each function, try to include:
- A typical case whose answer you have worked out by hand or from a trusted source.
- Boundaries — values exactly on the edges, like 0 and 100 above. Off-by-one mistakes live here.
- Special cases — zero, negative numbers, an empty list, a single item.
- Properties that must always hold, even when you do not know the exact answer: half the ticks should give half the distance; clamping should never return a value outside the range.
Never compute the expected answer by calling the function you are testing. That only checks that the function agrees with itself.
Many engineers write the tests before the function. Deciding what average([]) should do, before writing average, forces you to think about awkward cases up front. Larger projects use test runners such as pytest (a free tool installed separately), which find every function named test_... and run it — the same plain assert statements work there too.
Recap
- Calculation functions should return results; leave printing to the caller.
- Default and keyword arguments make functions convenient and calls readable.
- A docstring states the job, the parameters with units, and the return value.
assert condition, "message"is a minimal automatic test; compare floats withmath.isclose.- Test typical values, boundaries, special cases and properties, with expected answers worked out independently.
- Rerun your tests after every change.
Knowledge check
Check your understanding
Project
Programming project: a tested toolkit
Build a small Python module of engineering helpers, each with a docstring and a test function.
average(values)— decide, and document, what it should do for an empty list.celsius_to_fahrenheit(c)— test it with values you can check by hand: 0 °C is 32 °F and 100 °C is 212 °F, and −40 is the same in both scales.wheel_distance_mm(ticks, ticks_per_rev, diameter_mm)from this lesson.clamp(value, low, high)— add a test that checks the result is never outside the range for every whole number from −200 to 200.
Then deliberately break each function in a small way (change an operator, a sign or a boundary) and confirm that at least one of your tests fails. If a break goes unnoticed, add a test that catches it.
No hardware is required.
Deliverables
- A Python 3 file with four documented functions and a test_ function for each
- Output showing every test passing
- A short list of the deliberate bugs you introduced and which test caught each one
Go further
- The Python Tutorial — More on Defining Functions ↗
Official coverage of default arguments, keyword arguments and documentation strings (see section 4.9).
- Python Language Reference — Simple statements ↗
Includes the precise definition of the assert statement.
Lesson materials · free to download
Sign in to track your progress. Reading is free without an account.