← Intro to programming with Python

Reading error messages

Errors are clues, not failures.

Start this lesson

Every programmer, including experts, sees errors every day. An error message is Python telling you exactly what confused it and where. Read the LAST line first: it names the kind of error and gives a short reason. The line number tells you where to look. The four you will meet most: NameError (a name Python does not know, often a typo), TypeError (mixing kinds of values, like text + number), IndexError (a position past the end of a list or string) and ZeroDivisionError (dividing by zero).

scores = [70, 85]
print(scores[2])
# IndexError: list index out of range (line 2)

The list has positions 0 and 1 only, so position 2 does not exist. The fix is to use a valid index, such as scores[1] or scores[-1].

NameError: name 'totl' is not defined usually means a typo, or using a variable before creating it.

TypeError: can only concatenate str (not "int") to str means you used + between text and a number. Use str() or an f-string.

Common mistake: changing lots of things at once after an error. Fix ONE thing, run again, and read the new message.

Sometimes the real mistake is on the line ABOVE the one reported, especially a missing bracket or quote.