Sub topic 11
Reading errors and tracebacks
This chapter assumes you can run a script from the terminal with python3 hello.py (or py hello.py on Windows). You should also know what a function call is. By the end you will be able to read a traceback from the bottom up, name the common error types, and tell setup errors apart from code errors.
What a traceback is
When Python hits a problem it cannot handle, it stops the program and prints a traceback. A traceback is a report of the chain of function calls that led to the error. It goes to standard error (the terminal's error stream), and the process exits with a non-zero status.
Errors are not a sign you did something wrong. They are the main way Python tells you what to fix. Learning to read them quickly saves more time than any other early skill.
Your first traceback
Save this one-line script as oops.py. It has a deliberate typo.
print(mesage)Run it with python3 oops.py. Python prints this:
Traceback (most recent call last):
File "/home/ada/oops.py", line 1, in <module>
print(mesage)
NameError: name 'mesage' is not definedPython 3.11 and later may add a row of ^^^^^ marks under the code line. The marks point at the exact part of the line that failed. They are a hint only, and the rest of the layout is the same.
The report has three parts:
- The header line
Traceback (most recent call last):. - One or more frames. Each frame is a pair of lines: the file, line number, and function name, then the source line itself.
- The final line, which gives the exception type (
NameError) and a message (name 'mesage' is not defined).
The name <module> means the code ran at the top level of the file, outside any function.
Read from the bottom up
The last line tells you what went wrong. The frame just above it tells you where. Start there, and read upward only if you need to know how the program got there.
The reason is the header's wording: "most recent call last". Python lists calls in the order they happened, so the failing call is at the bottom, next to the error message.
A traceback with several frames
Real programs call functions that call other functions. Save this as ages.py. The line numbers matter, so keep the blank lines exactly as shown.
def parse_age(text):
return int(text)
def main():
print(parse_age("twenty"))
main()Running it produces:
Traceback (most recent call last):
File "/home/ada/ages.py", line 7, in <module>
main()
File "/home/ada/ages.py", line 5, in main
print(parse_age("twenty"))
File "/home/ada/ages.py", line 2, in parse_age
return int(text)
ValueError: invalid literal for int() with base 10: 'twenty'Read it from the bottom:
- Error:
ValueError. The message saysint()could not turn'twenty'into a number. - Where it failed: line 2, inside
parse_age. - How we got there:
mainon line 5 calledparse_age, and the top-level code on line 7 calledmain.
The failing line, return int(text), is correct code. The real problem is the value passed in at line 5. When the failing line looks fine, move up one frame and check what the caller sent.
Common exception types
Most beginner errors come from a short list. This table maps each to its usual cause.
| Exception | Typical cause | First thing to check |
|---|---|---|
| `SyntaxError` | Code that is not valid Python, such as an unclosed bracket | The reported line and the line before it |
| `IndentationError` | Inconsistent leading spaces or a missing indented block | Mixed tabs and spaces, and the line after a `:` |
| `NameError` | Using a name that was never defined | Spelling, and whether the assignment ran before this line |
| `TypeError` | An operation on the wrong kind of value, such as `"5" + 3` | The types of both operands |
| `ValueError` | Right type, unusable value, such as `int("abc")` | The value being passed in |
| `ZeroDivisionError` | Dividing by zero | The divisor |
| `FileNotFoundError` | Opening a path that does not exist | The path, and the directory you ran from |
| `ModuleNotFoundError` | `import` of a package that is not installed in this interpreter | Which interpreter is running, and whether the venv is active |
Syntax errors look different
A SyntaxError happens before the program starts, because Python cannot parse the file. There is no call chain, so the report is shorter. Save this as broken.py:
print("Hello"Python 3.10 and later prints:
File "/home/ada/broken.py", line 1
print("Hello"
^
SyntaxError: '(' was never closedNothing in the file ran, not even lines before the mistake. Python sometimes reports the line after the real mistake, because it only notices the problem when it reaches the next token. If the reported line looks fine, check the line above it for a missing closing bracket or quote.
Setup errors you will meet in this tutorial
Some tracebacks come from your environment, not your code.
ModuleNotFoundError: No module named 'requests' means the interpreter running your script has no requests package. Two causes are common. You installed it into a different Python, or you forgot to activate your virtual environment. Check which interpreter is running and install with that same interpreter:
python3 -c "import sys; print(sys.executable)"
python3 -m pip install requestsFileNotFoundError: [Errno 2] No such file or directory: 'data.txt' usually means a relative path was resolved from your current working directory. That is the directory you ran the command from, not the directory that holds the script. Run pwd (macOS and Linux) or cd (Windows Command Prompt) to see where you are.
On Windows, python: can't open file '...hello.py': [Errno 2] No such file or directory is not a traceback. It comes from the launcher, before your code starts. It means the filename or folder is wrong.
Chained exceptions
Sometimes a traceback contains two reports joined by a sentence. Two sentences are possible:
The above exception was the direct cause of the following exception:means the code raised a new error on purpose, usingraise ... from ....During handling of the above exception, another exception occurred:means a second error happened inside anexceptblock.
In both cases, read the bottom report first. It is the error that ended the program. The upper report explains where it came from.
def read_count(path):
try:
with open(path) as f:
return int(f.read())
except FileNotFoundError as err:
raise RuntimeError(f"cannot read count from {path}") from err
read_count("missing.txt")The output has the FileNotFoundError report first. Then comes the "direct cause" sentence, then the RuntimeError report. Your fix is in the first report (the missing file), but the program ended with the second.
Habits that make errors easier
- Copy the last line exactly when searching or asking for help. Include the exception type and the message, and leave out your personal paths.
- Share the whole traceback, not just the last line, when asking someone else. The frames show where the error came from.
- Change one thing, then rerun. If you edit three things, you will not know which one fixed it.
- Check that you saved the file. An unsaved editor buffer is a frequent reason an error "does not go away".
- Do not hide errors. A bare
except:that swallows everything removes the traceback you need.
Exercises
Exercise
Here is a traceback. Which file and line caused the error, what is the exception type, and which function called the failing function? Traceback (most recent call last): File "/home/ada/report.py", line 9, in <module> show(total("5")) File "/home/ada/report.py", line 5, in total return value + 10 TypeError: can only concatenate str (not "int") to str
Show answer
The error is a TypeError, raised in /home/ada/report.py on line 5, inside the function total, on the line return value + 10. The caller is the top-level code (<module>) on line 9, which passed the string "5" to total. The line itself is fine. The real fix is to convert the argument, for example total(int("5")), or to convert inside total.
Exercise
You run python3 app.py and see ModuleNotFoundError: No module named 'requests', even though you ran pip install requests earlier. Give two likely causes and a command that avoids the problem.
Show answer
Likely causes: the earlier pip belonged to a different Python than the one running app.py, or a virtual environment was not activated when you ran the script (or when you installed). The safer command is python3 -m pip install requests, run with the same interpreter and the same activated environment that runs the script. You can confirm which interpreter is in use with python3 -c "import sys; print(sys.executable)".