Reading Errors and Tracebacks
An error is not the program scolding you. It is Python telling you exactly what it could not do, and on which line - once you know how to read it.
Read the last line first
The bottom line names the problem. The line above it points at your code. Run this and read it that way.
One at a time
Four common errors, three of them commented out. Uncomment one, run, read the message, then move to the next.
The errors you will meet
str(36) or int("36").int("twelve") is a string, as required, but not one that is a number.Reading Errors and Tracebacks: A Practical Guide
The message is the instruction.
Quick Context
When Python cannot do what a line asks, it stops and prints a traceback. Read it from the bottom up: the last line is the error type and a plain-English description, and the line just above tells you which line of your code triggered it. Everything higher is the path that led there, which matters only once you have functions calling functions.
Errors happen at the point of failure, not the point of the mistake
The line named in a traceback is where things broke, which is not always where you went wrong. A variable assigned the wrong value on line 2 may only cause an error on line 40. The traceback gives you a place to start looking, not always the culprit - so check what the values actually are before assuming the named line is at fault.
Interactive Exploration Guide
- Run the first editor. Note that about to fail prints first: everything before the error ran normally, and execution stopped at the failing line.
- Read it bottom-up. The last line says
IndexError: list index out of range; the line above names line 3. Three items, so the highest valid index is 2. - Run the second editor as-is. A NameError for
totl- a typo oftotal, which is what that error almost always means. - Work through the rest. Comment out the NameError line, uncomment the TypeError one, and run. Repeat for ValueError and ZeroDivisionError, reading each message before fixing it.
Key Takeaway
A traceback is read bottom-up: the last line is the error type and description, the line above is where it happened. The common types each point at a specific fix - NameError at a typo, TypeError at a conversion, ValueError at the data, IndexError and KeyError at something you asked for that is not there. The named line is where it broke, which is not always where the mistake was.