Codiqo

Learn Python · lesson 37 of 60 · about 8 minutes

Reading Tracebacks

Make the assistant safe from a typo in the lunch money: read Python's error messages to find out what went wrong and on which line.

What you'll learn

  • Read a traceback from the bottom up
  • Recognise common error types
  • Use the line number to find the bug

Lunch money

The assistant asks how much lunch money Sam has for the week, in pence, and works out how many £2.50 school lunches it pays for. The first version did int(money) straight away, and the morning Sam typed ten pounds it stopped with a traceback ending ValueError: invalid literal for int() with base 10: 'ten pounds'. That last line says what went wrong: int() was given text that isn't a whole number. The fix is to check with money.isdigit() first, and only turn it into a number when it is one.

Errors are clues

When Python hits a problem it stops and prints a traceback. It looks scary, but read it from the bottom up:

1. The last line names the error type and gives a message
2. Just above it is the line of code that failed, with its line number
3. Everything higher up shows how the program got there

An example

Here's a traceback from a shop program:

  • File "shop.py", line 3 tells you where
  • total = price + qty is the line that failed
  • TypeError: can only concatenate str (not "int") to str is what went wrong: price is text and qty is a number

Printing just the last line of a traceback

import traceback

price = "5"
try:
    total = price + 3
except TypeError:
    print(traceback.format_exc().splitlines()[-1])

Output

TypeError: can only concatenate str (not "int") to str

The usual suspects

| Error | Usually means |
|---|---|
| NameError | A name is misspelt or not defined yet |
| TypeError | Mixing types, like text + number |
| ValueError | Right type, bad value, like int("hi") |
| IndexError | List position doesn't exist |
| KeyError | Dictionary key doesn't exist |
| ZeroDivisionError | Dividing by zero |

Getting the error name in code

try:
    int("hi")
except Exception as e:
    print(type(e).__name__)

Output

ValueError

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.