Recipe
Read a traceback
Use when: a Python program stopped and printed a report
Goal: the line to fix and what is wrong with it
Taught in Input, output, and first errors
Quick recipe
-
1
Read the exception type and its message, and any
Did you meanhint.Example
NameError: name 'totl' is not defined. Did you mean: 'total'?says an unknown name, probably a typo fortotal.Why: the last line is the only one that says what went wrong; everything above says where.
-
2
Go up one or two lines to the file name and line number, and the code with
^marks under the failing part.Example
File "main.py", line 3, in <module>andprint("Total:", totl)with^^^^undertotl.Why: the marks point at the exact part of the line, not just the line.
-
3
No
Tracebackline and nothing printed: a grammar error, found before running. Otherwise it happened while running, at that line.- SyntaxError or IndentationError — fix the grammar; if the named line looks fine, check the line above it.
- NameError or TypeError — look at the names and values used on that line.
Why: grammar is checked for the whole file before any line runs; names and values only when the line runs.
-
4
Change only what the report points at, then rerun to see the next report, if there is one.
Why: one change at a time tells you which change fixed it.
Common mistakes
- Reading from the top and stopping at
Traceback (most recent call last):. - Ignoring the
Did you meansuggestion. - Assuming the line named in a
SyntaxErrormust be the broken one, when an unclosed bracket on the line above is the usual cause.