Lite / Textbooks / Engineering Programming With Python / Chapter 4
4. Functions, tests and debugging
Introduction
A function packages a calculation behind a name: inputs in, one value returned. Once it exists, you can test it with assert against answers worked out independently, and reuse it with confidence. When something breaks, read the traceback from the bottom, reproduce the bug, form a hypothesis and test it. Finally, check inputs at the door, so bad data fails loudly instead of quietly producing nonsense.
Figure 4.1. Inputs in, one value returned (described in words)
A function machine labelled wheel_distance takes counts = 1200, cpr = 600 and diameter = 0.065 and returns π × 0.065 × 1200 / 600 = 0.408 m. Return, don't print: the caller decides.
Explanation
Built from 5 School lessons. Each part is the lesson's own explanation.
4.1 Package a calculation as a function
A robot converts wheel rpm to speed in six places in its code. One of them has a bug. How do you fix all six at once?
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.
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.
Open the Lite lesson: Package a calculation as a function
4.2 Promises and proof: tests with assert
Three versions of a °C-to-°F function all run without errors. Only one is right. How can three lines of tests tell them apart instantly?
A test is an assert
def c_to_f(c):
"""Convert a temperature in °C to °F."""
return c * 9 / 5 + 32
assert c_to_f(0) == 32
assert c_to_f(100) == 212
assert c_to_f(-40) == -40
print("all tests passed")assert condition does nothing if the condition is True and stops with AssertionError if it is False.
Expected values must be independent
Work out each expected value from somewhere other than the code: a reference point (water freezes at 0 °C = 32 °F), a hand calculation or a datasheet. If you copy the function's own output into the test, the test will happily confirm a bug.
Floats need a tolerance
(3.3 - 2.0) / 0.01 is 129.99999999999997, so == 130 fails even though the function is right. Write assert abs(led_resistor_ohm(3.3, 2.0, 10) - 130) < 1e-9, or math.isclose(...). Pick a tolerance that makes physical sense for the quantity.
Common mix-ups
If code runs without an error, it is correct.
✓ Running proves only that it does not crash. Tests against known answers show whether it is right.A failing test always means the function is wrong.
✓ Sometimes the test is wrong, for example by comparing floats with ==. Check both.
Open the Lite lesson: Promises and proof: tests with assert
4.3 Read the traceback
Your program crashes with six lines of red text. Most people read the top. Why does the answer start at the bottom?
Bottom up
Traceback (most recent call last):
File "log.py", line 7, in <module>
print(mean([]))
File "log.py", line 5, in mean
return total / len(readings)
ZeroDivisionError: division by zeroLast line: the error type and message. Just above: the file, line and code where it happened. Higher up: the chain of calls that got there (line 7 called mean).
Three kinds of error
Syntax errors stop the program before anything runs: if x = 5: (Python even suggests ==). Runtime errors crash it part-way: dividing by zero, adding text to a number. Logic errors never crash: the program runs and gives a wrong answer. Logic errors are the hardest, so tests matter.
The usual suspects
NameError: a misspelt name or one used before it is assigned. TypeError: the wrong type, such as "23.5" + 0.4. ValueError: right type, bad value, such as float("ERR"). ZeroDivisionError: dividing by zero, often an empty list. IndexError: a list position that does not exist, such as readings[7] in a 7-item list.
Common mix-ups
The first line of a traceback is the most important.
✓ The last line names the error, and the line above it shows where. Read from the bottom.No error message means no bug.
✓ Logic errors give wrong answers silently. Only tests and checks reveal them.
Open the Lite lesson: Read the traceback
4.4 Reproduce, hypothesise, test: hunting logic bugs
A robot's speed log says 240 m/s. Nothing crashed. Where do you even start?
The method
- Reproduce: find a small input that always shows the bug. 2. Hypothesise: 'I think the first reading is never added.' 3. Test the hypothesis: add a print, or try an even smaller input. 4. Fix the cause, not the symptom. 5. Keep a test that would have caught it.
Print probes
A print just after a suspect line shows the values at that moment: print("i", i, "total", total) inside a loop. If i starts at 1, the hypothesis is confirmed. Remove or comment out probes once the bug is fixed; keep the assert you add.
Three classic logic bugs
Off-by-one: range(1, n) skips index 0; range(n + 1) runs one too far. Indentation: a return inside a for loop returns after the first item. Units: millimetres divided by seconds labelled m/s is 1000 times too big. The first two show in a probe of the loop; the third shows in a units check.
Common mix-ups
Debugging means changing things until it works.
✓ Debugging means forming and testing hypotheses until you know the cause, then fixing that cause.Once it's fixed, the bug is gone for good.
✓ Bugs come back when code changes. A test that would have caught it keeps it gone.
Open the Lite lesson: Reproduce, hypothesise, test: hunting logic bugs
4.5 Catch bad data before it bites
A data logger writes ERR whenever its sensor hiccups. Should your program crash, skip the line, or quietly count it as zero?
Validate every line
def parse_reading(line):
"""Return the reading in °C, or None if the line is not a plausible reading."""
try:
value = float(line)
except ValueError:
return None
if value < -40 or value > 125:
return None
return value
lines = ["21.5", "ERR", "", "-999.0", "22.1"]
good = []
for line in lines:
value = parse_reading(line)
if value is not None:
good.append(value)
print(good) # [21.5, 22.1]Two different checks
The conversion check (try / except ValueError) catches lines that are not numbers at all: ERR, blanks, '--'. The plausibility check catches numbers that cannot be real: −999.0, 130.5. The band comes from the sensor's datasheet (here −40 to 125 °C, typical of small temperature sensors) or from physics.
Never hide the evidence
Count what you reject and report it: '3 of 480 lines rejected'. Never replace bad lines with 0, which drags the mean down and looks like a real reading. Catch only the error you expect (except ValueError), not every error, so genuine bugs still show up.
Common mix-ups
If float() succeeds, the reading is good.
✓ −999.0 and 130.5 convert fine but are impossible. Range checks are also needed.Catching every exception makes a program robust.
✓ It makes bugs invisible. Catch the specific errors you expect and handle them deliberately.
Open the Lite lesson: Catch bad data before it bites
Worked examples
Package a calculation as a function: example 1
Write mean(values) that returns the mean of a non-empty list, and use it for [41.2, 42.0, 43.5].
Solution
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.
Promises and proof: tests with assert: example 1
Write tests for current_ma(v, r_ohm), which returns the current in mA.
Solution
Hand calculations: 5 V / 250 Ω = 0.02 A = 20 mA; 3.3 V / 1000 Ω = 3.3 mA; 0 V gives 0 mA. Tests: assert abs(current_ma(5, 250) - 20) < 1e-9, assert abs(current_ma(3.3, 1000) - 3.3) < 1e-9, assert current_ma(0, 100) == 0.
Read the traceback: example 1
A traceback ends: IndexError: list index out of range, at line 4: last = readings[len(readings)]. Explain and fix.
Solution
A list of n items has positions 0 to n − 1, so readings[len(readings)] is one past the end. Use readings[len(readings) - 1] or simply readings[-1].
Reproduce, hypothesise, test: hunting logic bugs: example 1
count_over([48, 52, 55, 49, 61], 50) returns 0 instead of 3. Find the bug.
Solution
Reproduce: it always returns 0. Hypothesis: the loop stops early. Probe after the if: it prints once, with r = 48. So the function returns after the first reading: return count is indented inside the for loop. Fix: un-indent it to the for's level. Keep assert count_over([48, 52, 55, 49, 61], 50) == 3.
Catch bad data before it bites: example 1
What does parse_reading do with "nan"?
Solution
float("nan") succeeds and returns nan (not a number). Both nan < -40 and nan > 125 are False, so the range check lets it through! Add import math and if math.isnan(value): return None, or write the range check as if not (-40 <= value <= 125): return None, which rejects nan because the chained comparison is False.
Interactive figures, in words
Figure 4.2 from Package a calculation as a function
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.
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).
Figure 4.3 from Read the traceback
Work through 'Text plus a number', 'Mean of an empty log' and 'One equals sign'. For each, read the traceback from the bottom, pick the line you suspect and check. Use the print probe to see the variables just before the crash.
The bug hunt shows a short program, what was expected and what actually happened. 'Text plus a number' crashes on line 3 with TypeError: can only concatenate str (not "float") to str. 'Mean of an empty log' crashes on line 5 inside mean, called from line 7, with ZeroDivisionError. 'One equals sign' fails before running with a SyntaxError on line 3, suggesting '=='. Selecting a line and checking explains the cause and the fix.
Laboratory
These run in a browser on the full site (they need a faster connection). Simulations are simplified educational models.
- Code Lab (Studio)
Write wheel_distance with a docstring and three assert tests, one of which uses a tolerance.
Open on the full site - BUILD: Sorting machine, level 2 (BUILD level)
Write the sorting rules as a function and test it on every kind of part, including a missing reading.
Open on the full site
Practice
Each question links to its Lite lesson, where your answer is checked on our server and a wrong answer gets a hint. Answers are never sent to your device.
- 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?
Answer it in “Package a calculation as a function” - Why is return better than print inside a calculation function?
Answer it in “Package a calculation as a function” - You are testing def current_ma(v, r_ohm): return v / r_ohm * 1000. To write assert abs(current_ma(9, 100) - EXPECTED) < 0.01, work EXPECTED out by hand with Ohm's law. What is it, in mA?
Answer it in “Promises and proof: tests with assert” - A correct function returns 129.99999999999997 for an expected 130. Which test is right?
Answer it in “Promises and proof: tests with assert” - Which part of a traceback tells you the kind of error?
Answer it in “Read the traceback” - A program gives a wrong total. What is the best first step?
Answer it in “Reproduce, hypothesise, test: hunting logic bugs” - distance_mm differences divided by interval_s are printed as m/s and look 1000 times too big. Best fix?
Answer it in “Reproduce, hypothesise, test: hunting logic bugs” - Why write except ValueError rather than a bare except?
Answer it in “Catch bad data before it bites”
Engineering applications
Tested building blocks
Flight software and medical devices are built from small functions, each with tests that pin down its behaviour. When a function changes, its tests run again automatically, so a regression is caught before it ships.
Fail loudly
A sensor that returns −999 on error can silently drag an average down. Checking inputs and raising a clear error stops bad data from spreading through every calculation that follows.
Watch (optional)
Streaming video uses a lot of data. Everything you need is in the text.
- “Python Tutorial for Beginners 8: Functions” by Corey Schafer
- “Python Tutorial: Using Try/Except Blocks for Error Handling” by Corey Schafer
- “What is "rubber duck debugging?"” by MIT OpenCourseWare
Summary
- A function takes inputs and returns a value; return rather than print so callers can use it.
- Test against answers you worked out independently, with a tolerance for floats.
- Read tracebacks from the bottom: the last line names the error, the lines above show where.
- Debug by reproducing, hypothesising and testing one idea at a time; validate inputs at the boundary.
Glossary
- Functions and return values
- def name(parameters): defines a reusable block of code. Calling it runs the body with the given arguments, and return sends a value back to the caller. Field Guide
- Exceptions: try and except
- When something goes wrong, Python raises an exception. A try block runs risky code and an except block handles a named kind of exception instead of crashing. Field Guide
- Floating-point rounding and comparison
- Most decimal fractions cannot be stored exactly in binary floating point, so tiny rounding errors appear and == between floats is unreliable. Field Guide
Project: A tested utility module
Write three functions you would reuse in engineering work, such as wheel distance from encoder counts, ADC counts to volts and a safe mean that rejects empty or invalid data. Give each a docstring, input checks and at least three tests, including one edge case.
Deliverables
- The three functions with docstrings
- At least nine tests that pass
- A short log of one bug you found and how you located it
Write it up on paper or in your own notes. Lite never stores what you write.
References
- Allen B. Downey (2015). Think Python: How to Think Like a Computer Scientist, 2nd edition. O'Reilly Media.
- John V. Guttag (2016). Introduction to Computation and Programming Using Python, 2nd edition. MIT Press.
Further reading from the lessons
- Python tutorial: defining functions
The official guide to def, parameters, return and docstrings. - Python tutorial: errors and exceptions
Official explanations of syntax errors, exceptions and tracebacks. - Python tutorial: handling exceptions
The official guide to try and except.