Errors, tracebacks and debugging
Read Python's error messages with confidence, handle expected problems with try and except, and find silent logic bugs with a systematic debugging method.
Lesson 6 of 6 · 35 min · Self-paced · Free
Why debugging is a core engineering skill
Every program of any size has bugs while it is being written. Professional engineers are not people who never make mistakes; they are people who find mistakes quickly and methodically. On a robot this matters twice over: a bug can mean a crash in the software and a crash in the physical world. This lesson gives you a toolkit: how to read error messages, how to make a program cope with problems you expect, and how to hunt down the ones you did not expect.
Three kinds of error
- Syntax errors. The code is not valid Python, so it will not run at all. Python points at the problem before anything happens.
- Runtime errors (exceptions). The code is valid but something goes wrong while it runs — dividing by zero, opening a missing file — and Python stops with a traceback.
- Logic errors. The program runs to the end and prints an answer, but the answer is wrong. Python cannot detect these, which makes them the most dangerous.
A syntax error looks like this, for a missing colon:
File "check.py", line 1
if speed > 10
^
SyntaxError: expected ':'The caret ^ marks where Python got confused. The real mistake is usually there or on the line just before it.
Reading a traceback
Save this program as rover.py and run it:
# rover.py
def average(values):
return sum(values) / len(values)
def report(name, values):
print(f"{name}: {average(values):.1f} mm")
report("front", [412, 398, 381])
report("rear", [])Output:
front: 397.0 mm
Traceback (most recent call last):
File "rover.py", line 9, in <module>
report("rear", [])
~~~~~~^^^^^^^^^^^^
File "rover.py", line 6, in report
print(f"{name}: {average(values):.1f} mm")
~~~~~~~^^^^^^^^
File "rover.py", line 3, in average
return sum(values) / len(values)
~~~~~~~~~~~~^~~~~~~~~~~~~
ZeroDivisionError: division by zero(Python prints the full path to the file; it is shortened here. The ~ and ^ markers appear in recent versions of Python and may look slightly different on yours.)
Read a traceback from the bottom up:
- The last line says what went wrong: a
ZeroDivisionError. - The entry just above it says where: line 3, inside
average. - Moving upwards, each entry shows who called whom:
averagewas called byreporton line 6, which was called from the main program on line 9.
The first report worked; the second passed an empty list, so len(values) was 0. The traceback shows the line that crashed, but the real cause is often further up the chain — here, the caller supplied data the function could not handle.
Common exceptions and what they usually mean
NameError: name 'sped' is not defined— a typo in a variable name, or using a variable before creating it. Recent Python versions add a hint such as "Did you mean: 'speed'?".TypeError: can only concatenate str (not "float") to str— mixing types, such as"Speed: " + 12.5. Use an f-string instead.ValueError: could not convert string to float: 'n/a'— the type is right but the content is not, typical of messy data files.IndexError: list index out of range— asking for position 10 of a shorter list, often an off-by-one loop.KeyError: 'max_amps'— a dictionary has no such key; check the spelling or use.get.FileNotFoundError— the file is not in the folder Python is looking in.
Handling errors you expect
Some problems are not bugs but facts of life. Sensors return garbage, and logs contain ERR. For these, use try and except: Python tries the indented block, and if the named exception happens, it runs the except block instead of stopping.
def parse_reading(text):
"""Return text as a float, or None if it is not a valid number."""
try:
return float(text)
except ValueError:
return None
raw = ["12.5", "12.7", "ERR", "", "12.6"]
values = []
bad = []
for i, text in enumerate(raw):
value = parse_reading(text)
if value is None:
bad.append(i)
else:
values.append(value)
print(values)
print("Could not read indices:", bad)Output:
[12.5, 12.7, 12.6]
Could not read indices: [2, 3]Two rules keep try honest. First, catch only the specific exception you expect (ValueError here). A bare except: catches everything, including your own typos, and turns real bugs into silent wrong answers. Second, record what you skipped, as bad does here.
Your own functions can raise exceptions too. That is often better than returning a misleading value:
def average(values):
"""Mean of a non-empty list. Raises ValueError for an empty list."""
if len(values) == 0:
raise ValueError("average() needs at least one value")
return sum(values) / len(values)
try:
print(average([]))
except ValueError as error:
print("Problem:", error)Output:
Problem: average() needs at least one valueA clear message at the moment of the mistake beats a confusing failure three functions later.
Hunting a logic bug
Logic bugs give no traceback, so you need a method. Here is a moving-average function with a mistake. On a small input whose answer you can work out by hand, the averages of [1, 2, 3], [2, 3, 4] and [3, 4, 5] should be 2, 3 and 4:
def moving_average(values, window):
out = []
for i in range(len(values) - window):
out.append(sum(values[i:i + window]) / window)
return out
print(moving_average([1, 2, 3, 4, 5], 3))Output:
[2.0, 3.0]One window is missing. The quickest way to see why is to print the program's state inside the loop. Writing = at the end of an expression in an f-string prints the expression and its value:
def moving_average(values, window):
out = []
for i in range(len(values) - window):
print(f"{i=} {values[i:i + window]=}")
out.append(sum(values[i:i + window]) / window)
return out
print(moving_average([1, 2, 3, 4, 5], 3))Output:
i=0 values[i:i + window]=[1, 2, 3]
i=1 values[i:i + window]=[2, 3, 4]
[2.0, 3.0]The loop never reaches i = 2. Five values and a window of three give 5 − 3 + 1 = 3 windows, but range(5 - 3) produces only 0 and 1. The fix is range(len(values) - window + 1) — the version from the lesson on lists. Now remove the debugging print and turn the hand-worked example into a test, assert moving_average([1, 2, 3, 4, 5], 3) == [2.0, 3.0, 4.0], so this bug can never come back.
A debugging method
When something is wrong, work through these steps instead of changing code at random:
- Reproduce it. Find the smallest input that shows the problem every time.
- Read the message. Bottom line first, then the line it points to.
- Form a guess about the cause, and predict what you would see if it were true.
- Test the guess. Print values, add an
assert, or try a smaller input. Python's built-in debugger, started by puttingbreakpoint()on a line, lets you pause there and inspect variables. - Divide and conquer. If you cannot tell where it goes wrong, check the data halfway through the program. Is it already wrong there? Then the bug is in the first half. Repeat.
- Change one thing at a time, and rerun your tests after every fix.
- Explain it aloud. Describing the code line by line to someone else — or to a rubber duck — often reveals the assumption you got wrong.
Keep a short note of bugs that took a long time. Patterns appear quickly: off-by-one ranges, unconverted strings, units mixed up.
Recap
- Syntax errors stop the program before it runs; exceptions stop it while running; logic errors do not stop it at all.
- Read tracebacks from the bottom: what happened, where, and the chain of calls that led there.
- Use
try/exceptfor problems you expect, catch specific exceptions, and record what you skipped. raisea clear exception when a function receives input it cannot handle.- For logic bugs, use a small input with a known answer, print the state, and narrow down methodically.
Knowledge check
Check your understanding
Project
Debugging project: three bugs
The program below is meant to convert a list of temperature readings from °C to °F, skipping any that cannot be read, and print every converted value. It contains three bugs.
readings = ["20.5", "21.0", "bad", "22.5", "23.0"]
def to_numbers(texts):
numbers = []
for t in texts:
numbers.append(float(t))
return numbers
def celsius_to_fahrenheit(c):
return c * 9 / 5 + 23
values = to_numbers(readings)
for i in range(1, len(values)):
print(celsius_to_fahrenheit(values[i]))- Run it and read the traceback. Write down what it tells you before changing anything.
- Fix the bug the traceback reveals using
try/except, and make the program report how many readings it skipped. - Find the two remaining logic bugs using test cases you can check by hand (0 °C is 32 °F; 100 °C is 212 °F) and by printing the loop variable.
- Add
asserttests so that each bug would be caught if it came back.
No hardware is required.
Deliverables
- The corrected Python 3 program with assert tests
- A short bug log: for each bug, the symptom, how you found it and the fix
- Output showing all four valid readings converted correctly
Go further
- The Python Tutorial — Errors and Exceptions ↗
Official explanation of syntax errors, exceptions, try/except and raising your own exceptions.
- Python documentation — Built-in Exceptions ↗
A reference describing every standard exception, such as ValueError, KeyError and IndexError.
- Python documentation — pdb, the Python debugger ↗
How to pause a program with breakpoint(), step through it line by line and inspect variables.
Lesson materials · free to download
Sign in to track your progress. Reading is free without an account.