Skip to main content

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:

  1. Bottom line — the actual error type and message: ZeroDivisionError: division by zero
  2. Line above — the exact code that failed: return x / y
  3. 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 line
  • p variable — print variable value
  • q — quit

Or use breakpoint() (Python 3.7+) instead of import pdb; pdb.set_trace().

Quick Error Reference​

ErrorCommon CauseQuick Fix
SyntaxErrorTypo, missing :, unclosed bracketRead the line carefully
NameErrorTypo, variable not defined yetCheck spelling and scope
TypeErrorWrong type (str + int, etc.)Cast to correct type
IndexErrorList index too largeCheck len() first
KeyErrorDict key missingUse .get(key, default)
AttributeErrorWrong method nameUse dir() or check docs
FileNotFoundErrorWrong pathCheck with ls or Path.exists()
ValueErrorRight type, wrong valueValidate before converting
IndentationErrorWrong spacingUse 4 spaces, never tabs
ZeroDivisionErrorDividing by 0Check 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")

What's Next​

→ Module 2: Language Basics