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'?- The last line names the type of error and gives a message. This is the most important line. Here it is a
NameError, and the message says which name is unknown. - The line above it shows the line of your code that failed, with small marks under the exact spot.
- Above that is the file name and the line number. Go to that line in your editor.
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
- Read the last line of the message. Say in your own words what Python is complaining about.
- Go to the line number it gives. Look at that line and the one above.
- Print the values and types of the variables on that line, just before it.
- Change one thing and run again. If you change three things at once, you will not know which one mattered.
- 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.