Reading errors and debugging

Error messages look scary, but they are the most helpful thing Python ever says to you. A traceback looks like this:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    print(total / count)
          ~~~~~~^~~~~~~
ZeroDivisionError: division by zero

Read it from the bottom up. The last line tells you what went wrong: the error type, then a message. The lines above tell you where: the file, the line number and the actual code. Newer Pythons even draw ^ marks under the exact part that failed.

The usual suspects:

  • SyntaxError: the code is not valid Python. Missing colon, unclosed bracket or quote. The line number can point just after the real mistake, so check the line above too.
  • IndentationError: spaces do not line up.
  • NameError: you used a name that does not exist. Usually a typo (totla) or using a variable before assigning it.
  • TypeError: wrong type for the job, like "Age: " + 15.
  • ValueError: right type, bad value, like int("abc").
  • IndexError / KeyError: that position or key is not there.

The nastiest bugs give no error at all: the program runs and prints the wrong answer. For those, use the oldest tool there is: add print() lines to see what your variables actually hold at each step. Compare that with what you think they hold. The bug lives in the gap.

A calm process: read the last line, go to the line number, form one guess, change one thing, run again. Pasting the error into a chatbot fixes this bug; learning to read it fixes the next hundred.

Try it yourself

Edit it. Break it. Run it again.
scores = [8, 9, 7]

# Catching an error so we can look at it without crashing
try:
    print(scores[3])
except IndexError as e:
    print("IndexError:", e)

try:
    print("Age: " + 15)
except TypeError as e:
    print("TypeError:", e)

# The fix for the second one
print("Age: " + str(15))

# print-debugging: show what is really going on
total = 0
for s in scores:
    total += s
    print("after adding", s, "total is", total)
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Your turn

Type it yourself. That is the whole trick.

1Fix the crash

This program crashes with a TypeError. Read the error, fix the bug, and make it print exactly You have 3 new messages.

count = 3
print("You have " + count + " new messages")
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

2The silent bug

average(nums) should return the average of a list of numbers, but it gives the wrong answer without any error. Find and fix the bug. Adding print() lines inside the loop to watch total will help.

def average(nums):
    total = 0
    for n in nums:
        total = n
    return total / len(nums)
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.