How do I read a Python error message?

Read a traceback from the bottom up, recognise five errors that often stop beginners’ scripts, and catch only the errors you expect with try and except.

After this lesson, you can trace an error to the line that caused it and catch only the errors you expect.

How do I find the line that failed?

A traceback lists the calls that led to an error, and its last line names the error and what went wrong, so you read it from the bottom up. Dividing a price stored as text, "101.0", by a number stops daily_return with a TypeError, and the line above names week_returns, the function that passed the two prices.

The closes are a made-up stock’s closes in dollars. Wednesday’s close was entered as text, Friday has the marker "n/a" for a missing price, and the next Monday has the text "four hundred". try runs code and except TypeError as error catches that error, so the page can print the traceback’s call names, which extract_tb reads, and the error’s name and message.

The following box runs the returns on the first four closes and prints the traceback.

from traceback import extract_tb

raw = [100.0, 102.0, "101.0", 103.5, "n/a", "four hundred"]

def daily_return(yesterday, today):
    return today / yesterday - 1

def week_returns(closes):
    return [daily_return(closes[i - 1], closes[i]) for i in range(1, len(closes))]

try:
    week_returns(raw[:4])
except TypeError as error:
    print([call.name for call in extract_tb(error.__traceback__)])
    print(type(error).__name__, error)
['<module>', 'week_returns', 'daily_return']
TypeError unsupported operand type(s) for /: 'str' and 'float'

The failing line is return today / yesterday - 1, and the cause is Wednesday’s text, passed in by week_returns.

Which five errors stop most scripts?

Each error’s name points to its cause.

Error Cause Example
NameError A name Python cannot find, often a typo print(price) when the list is prices
KeyError A missing dictionary entry prices["BBB"] when only AAA is stored
IndexError A position past the end of a list closes[4] on four closes
ValueError Text that cannot become a number float("n/a")
ZeroDivisionError A division by zero 1 / 0

"BBB" in prices and prices.get("BBB") check for an entry without the error, as in the lesson on dictionaries.

How do I catch only the error I expect?

except ValueError catches a failed conversion and lets every other error stop the program, so a typo still shows. to_price turns text into a number, gives None for the agreed marker "n/a", and raises the error again for any other bad text with raise. A bare except: would catch everything, including a misspelled function name, and hide the bug.

repr(text) shows quotes around text, so text and numbers look different in the output.

The following box converts the six entries.

def to_price(text):
    try:
        return float(text)
    except ValueError:
        if text == "n/a":
            return None
        raise

for text in raw:
    try:
        print(repr(text), to_price(text))
    except ValueError as error:
        print(repr(text), type(error).__name__)
100.0 100.0
102.0 102.0
'101.0' 101.0
103.5 103.5
'n/a' None
'four hundred' ValueError

Wednesday’s '101.0' becomes 101.0, Friday’s marker becomes None, and 'four hundred' raises its ValueError.

Your turn

Fix week_returns so it converts each close with float() first, and print the returns of the first four closes rounded to four decimals. You should see [0.02, -0.0098, 0.0248].

The comprehension converts the closes before the division.

def week_returns(closes):
    numbers = [float(close) for close in closes]
    return [daily_return(numbers[i - 1], numbers[i]) for i in range(1, len(numbers))]

print([round(r, 4) for r in week_returns(raw[:4])])
[0.02, -0.0098, 0.0248]