Files, Errors and Modules · Robust Code · lesson 4 of 8
Reading a traceback
about 12 minutes · free · runs in your browser
The most useful thing on the screen
A traceback looks alarming and is actually a set of directions. Read it from the bottom:
Traceback (most recent call last):
File "shop.py", line 22, in <module>
print(total_price(basket))
File "shop.py", line 15, in total_price
return sum(item["price"] for item in items)
KeyError: 'price'
The last line is what went wrong: a dictionary had no 'price' key. The frames above it
are the route Python took to get there, most recent last — so the second-to-last frame is
usually where your bug lives.
Three habits worth forming:
- Read the last line first.
- Find the last frame in your own code — frames inside libraries are usually downstream of a mistake in yours.
- The line number is where it surfaced, not always where it started; a
Nonethat crashes here may have been created somewhere else.
Your turn: total_price below crashes on items with no price. Fix it so missing
prices count as zero.
You start from this, and edit it in the browser:
def total_price(items):
return sum(item["price"] for item in items)