Reading Python Errors
What You'll Learn
How to read Python error messages (tracebacks), recognize common error types, and fix them confidently.
Don't Fear the Traceback
A traceback is Python telling you exactly what went wrong and where. Most beginners panic when they see one — don't. It's free information.
Traceback (most recent call last):
File "script.py", line 10, in main
result = divide(x, y)
File "script.py", line 5, in divide
return x / y
ZeroDivisionError: division by zero
Read it bottom to top:
- Bottom line — the actual error type and message:
ZeroDivisionError: division by zero - Line above — the exact code that failed:
return x / y - Lines above that — the call stack showing how you got there
Common Error Types
SyntaxError — Code isn't valid Python
print("hello" # Missing closing )
SyntaxError: '(' was never closed
Fix: Check for unclosed brackets, missing colons, or mismatched quotes.
NameError — Variable or function doesn't exist
print(messge) # typo: "messge" instead of "message"
NameError: name 'messge' is not defined
Fix: Check spelling, check if the variable was actually defined, check scope.
TypeError — Wrong type of value
age = 25
print("Age: " + age) # can't add str and int
TypeError: can only concatenate str (not "int") to str
Fix: Cast to the right type: print("Age: " + str(age))
IndexError — List index out of range
items = ["a", "b", "c"]
print(items[5]) # only indexes 0, 1, 2 exist
IndexError: list index out of range
Fix: Check list length with len(items) before accessing by index.
KeyError — Dictionary key doesn't exist
user = {"name": "Alice"}
print(user["email"]) # "email" key doesn't exist
KeyError: 'email'
Fix: Use .get() with a default: user.get("email", "not set")
AttributeError — Object doesn't have that method or attribute
name = "alice"
print(name.uppercase()) # method is "upper()", not "uppercase()"
AttributeError: 'str' object has no attribute 'uppercase'
Fix: Check the correct method name in the docs or with dir(name).
FileNotFoundError — File doesn't exist at that path
with open("data.txt") as f:
content = f.read()
FileNotFoundError: [Errno 2] No such file or directory: 'data.txt'
Fix: Check the path is correct: ls data.txt in your terminal.
ValueError — Right type, wrong value
number = int("hello") # "hello" can't be converted to int
ValueError: invalid literal for int() with base 10: 'hello'
Fix: Validate before converting, or use a try/except.
IndentationError — Wrong indentation
if True:
print("hello") # not indented
IndentationError: expected an indented block after 'if' statement
Fix: Add 4 spaces of indentation.
How to Debug Systematically
When your script fails, follow this order:
1. Read the bottom of the traceback first
↓
2. Find the exact line number and file
↓
3. Read the code around that line
↓
4. Add print() to inspect variable values
↓
5. Fix the root cause (not just the symptom)
Add print() to Inspect State
def calculate_average(numbers):
print(f"DEBUG: numbers={numbers}, type={type(numbers)}") # ← add this
total = sum(numbers)
return total / len(numbers)
Remove the debug prints once fixed.
Using Python's Built-in Debugger (pdb)
import pdb
def risky_function(data):
pdb.set_trace() # execution stops here, you can inspect variables
result = data["key"]
return result
In pdb:
n— next linep variable— print variable valueq— quit
Or use breakpoint() (Python 3.7+) instead of import pdb; pdb.set_trace().
Quick Error Reference
| Error | Common Cause | Quick Fix |
|---|---|---|
SyntaxError | Typo, missing :, unclosed bracket | Read the line carefully |
NameError | Typo, variable not defined yet | Check spelling and scope |
TypeError | Wrong type (str + int, etc.) | Cast to correct type |
IndexError | List index too large | Check len() first |
KeyError | Dict key missing | Use .get(key, default) |
AttributeError | Wrong method name | Use dir() or check docs |
FileNotFoundError | Wrong path | Check with ls or Path.exists() |
ValueError | Right type, wrong value | Validate before converting |
IndentationError | Wrong spacing | Use 4 spaces, never tabs |
ZeroDivisionError | Dividing by 0 | Check divisor before dividing |
Practice: Fix These Errors
Try to predict the error before running each one:
# 1.
print("The answer is " + 42)
# 2.
fruits = ["apple", "banana"]
print(fruits[2])
# 3.
data = {"name": "Alice"}
print(data["age"])
# 4.
if True:
print("hello")
# 5.
number = int("3.14")