Lite / Intelligent Robotic Systems / Week 1
Functions that keep their promises
In 1999 a Mars orbiter was lost because one team's software worked in pound-force seconds and another's expected newton-seconds. What one line of documentation could have helped?
Why should I care?
A function's contract is its promise: give me these inputs, in these units, and I will return this. Teams build on each other's contracts every day. Writing them down, and checking them, turns silent wrong answers into loud, early errors.
- Write a docstring that states a function's inputs, units, output and failure behaviour.
- Design functions with a single responsibility that return values instead of printing them.
- Check preconditions and raise a clear error when a contract is broken.
Predict
battery_runtime_h(capacity_mah, current_ma) returns capacity / current. Someone calls it with current_ma = 0. What should a well-designed version do?
- Return 0
- Return a huge number
- Raise a ValueError explaining that current must be positive
- Print a warning and carry on
Guess first, then reveal
Raise a clear error. A zero current breaks the contract, and any number it returned would be a lie that flows into later calculations. A ValueError with a message points straight at the faulty caller.
Discover
In the Code Lab, write battery_runtime_h with a docstring and a check that both inputs are positive. Call it with good values, then with current_ma = 0 and capacity_mah = -500. Read each error message: does it tell the caller what to fix?
What the interactive shows (text version)
The Code Lab activity can be done on paper: write the function's docstring with inputs, units, ranges and return value, then list what it should do for capacity 2200 and current 550 (return 4.0), current 0 (raise ValueError) and capacity −500 (raise ValueError).
Understand
A docstring is the contract
State what each parameter means, its units and allowed range, what is returned (with units), and what happens on bad input. Someone should be able to use the function correctly from the docstring alone, without reading the body.
One job, returned not printed
A function that reads a file, converts units, averages and prints is four functions tangled together. Split it so each does one thing and returns its result. Returned values can be tested, reused and fed into the next step; printed text can only be read by a person.
Fail loudly at the boundary
Check preconditions at the top of the function and raise ValueError("...") with a message that names the bad value. An early, specific error is far cheaper than a wrong number discovered three modules later.
Explain it another way
Intuitive
A vending machine has a contract printed on it: insert coins, press a code, get a snack. It rejects foreign coins straight away instead of keeping them and giving you nothing. Good functions behave the same way.
Technical
Preconditions are what must be true of the inputs; postconditions are what the function guarantees about its output. Python's convention is to raise ValueError for a value of the right type but wrong range and TypeError for the wrong type. Type hints such as def f(x: float) -> float document types but are not enforced at run time.
Applied
Flight software standards require every interface to state units and ranges, because many costly failures have come from two correct pieces of code that disagreed about what a number meant.
Worked example 1
Write a contract-checked runtime function for a robot battery.
def battery_runtime_h(capacity_mah, current_ma):
"""Estimate runtime in hours.
capacity_mah: usable capacity in milliamp-hours, > 0
current_ma: average current draw in milliamps, > 0
Returns the runtime in hours. Raises ValueError for non-positive inputs.
"""
if capacity_mah <= 0:
raise ValueError(f"capacity_mah must be positive, got {capacity_mah}")
if current_ma <= 0:
raise ValueError(f"current_ma must be positive, got {current_ma}")
return capacity_mah / current_ma
print(battery_runtime_h(2200, 550)) # 4.0
try:
battery_runtime_h(2200, 0)
except ValueError as err:
print("Rejected:", err)Common mix-ups
Error checks make code longer for no reason.
✓ Two lines of checking can save hours of hunting a wrong number back to its source.Type hints stop wrong inputs.
✓ Python does not enforce them at run time. They document intent; range checks still need code.
Practice
Practice, not a test. Answers are checked on our server; a wrong answer gets a hint and another try. Nothing is saved.
Apply it
Write wheel_rpm(speed_m_s, diameter_m) for a rover: a docstring with units and ranges, checks that raise ValueError for bad inputs, and a returned value. Test it on 0.5 m/s with a 0.12 m wheel (about 79.6 rpm) and on two bad inputs.
Reflect
Think of a number you have computed before without writing its unit. How could it have been misread?
Write your answer on paper or in your own notes. Lite never stores what you write.
Go further
- Python tutorial: Errors and exceptions
How raise, try and except work, with the built-in exception types.