ShareYourGroupShareYourGroupPython

Python error messages explained

Every programmer sees error messages every day. They are not a sign that you are bad at this. They are Python telling you, quite precisely, what it could not do and where. These pages take the errors beginners meet most and show the usual causes, each with a real example and its fix.

How to read a traceback

When a program stops with an error, Python prints a few lines called a traceback. Read it from the bottom.

marks = [70, 80, 90]
average = sum(marks) / len(mark)
print(average)

What Python says

Traceback (most recent call last):
  File "example.py", line 2, in <module>
    average = sum(marks) / len(mark)
                               ^^^^
NameError: name 'mark' is not defined. Did you mean: 'marks'?

In a longer program the traceback lists several lines, one for each function call that led to the failure. The bottom one is where the error happened. The ones above show how the program got there.

Three families of error

Errors before the program starts. SyntaxError and IndentationError mean Python could not read the file. Nothing runs until they are fixed. They are always typing problems.

Errors while the program runs. NameError, TypeError, ValueError, IndexError, KeyError, ZeroDivisionError, AttributeError and the file and import errors appear when a particular line is reached with values it cannot handle. Everything above that line has already run.

No error, wrong answer. The hardest kind. The program runs to the end and prints something that is not right. Python cannot help here, because it did exactly what you wrote. Print the values of your variables at each step and compare them with what you expect. The first place they differ is where the mistake is.

A routine that works for any error

  1. Read the last line of the message. Say in your own words what Python is complaining about.
  2. Go to the line number it gives. Look at that line and the one above.
  3. Print the values and types of the variables on that line, just before it.
  4. Change one thing and run again. If you change three things at once, you will not know which one mattered.
  5. If you are still stuck, copy the last line of the message and read the matching page here.

Lesson 19, errors and try/except, shows how a program can catch errors that are not your fault, such as a user typing a word where a number is needed.

This is an independent learning site. It is not connected with or approved by the Python Software Foundation. "Python" is a trademark of the Python Software Foundation and is used here only to name the language.