Python Notes
Master Python error handling by understanding the most common errors — SyntaxError, IndentationError, NameError, TypeError, AttributeError, ImportError, ValueError, KeyError, IndexError, and how to fix them.
Every Python developer encounters errors. Learning to read error messages and understand common pitfalls is one of the most valuable skills you can develop.
Reading a Traceback
Traceback (most recent call last):
File "app.py", line 15, in <module> ← Script, line number, context
result = divide(10, 0) ← Code that caused the chain
File "app.py", line 8, in divide ← Function where error occurred
return a / b ← Exact line
ZeroDivisionError: division by zero ← Exception type: messageReading strategy: Always read the last line first (the actual error), then trace upward through the call stack.
SyntaxError
IndentationError
# ❌ IndentationError: Expected an indented block
def greet(name):
print(f"Hello, {name}") # Not indented!
# ✅ Fix
def greet(name):
print(f"Hello, {name}")
# ❌ IndentationError: Unexpected indent
x = 5
y = 10 # Indented but not inside a block
# ✅ Fix
x = 5
y = 10
# ❌ Mixing tabs and spaces
def calculate():
x = 1
y = 2 # Tab instead of spaces!
# ✅ Fix — use spaces consistently
def calculate():
x = 1
y = 2
# Pro tip: Configure your editor to show whitespace and convert tabs to spacesNameError
# ❌ NameError: name 'x' is not defined
print(x) # x was never assigned
# ✅ Fix
x = 10
print(x)
# ❌ NameError: typo in variable name
user_name = "Alice"
print(usernmae) # Typo!
# ✅ Fix
print(user_name)
# ❌ NameError: using variable before assignment
def calculate():
result = initial + 5 # initial not yet defined
initial = 10
return result
# ✅ Fix
def calculate():
initial = 10
result = initial + 5
return result
# ❌ NameError: function not imported
response = requests.get("https://example.com") # requests not imported
# ✅ Fix
import requests
response = requests.get("https://example.com")
# ❌ Scope issue
def outer():
x = 10
def inner():
print(x + 5) # OK — can read from outer scope
x = 20 # UnboundLocalError! Can't assign to x from outer scope
# ✅ Fix using nonlocal
def outer():
x = 10
def inner():
nonlocal x
x = 20
inner()
print(x) # 20TypeError
AttributeError
# ❌ AttributeError: 'str' object has no attribute 'append'
name = "Alice"
name.append(" Smith") # append() is for lists!
# ✅ Fix
name = name + " Smith" # or
name = f"{name} Smith"
# ❌ AttributeError: 'NoneType' object has no attribute 'upper'
result = some_function() # Returns None
print(result.upper()) # None has no methods!
# ✅ Fix — check for None
result = some_function()
if result is not None:
print(result.upper())
# Or: print(result.upper() if result else "No result")
# ❌ AttributeError: module has no attribute
import math
math.sqroot(16) # It's math.sqrt, not sqroot!
# ✅ Fix
math.sqrt(16)
# Common misspellings
# list.lenght → list.length (wrong!) → len(list) ✅
# dict.has_key() → 'key' in dict ✅ (Python 3)
# string.count() ← this one IS correct
# pd.DataFrame.tostring() → pd.DataFrame.to_string() ✅ImportError / ModuleNotFoundError
# ❌ ModuleNotFoundError: No module named 'numpy'
import numpy as np # Module not installed
# ✅ Fix — install it
# pip install numpy
import numpy as np
# ❌ ImportError: cannot import name 'DataFrame' from 'pandas'
from pandas import DataFrame # This actually works...
# But this won't:
from pandas import Dataframe # Case sensitive!
# ✅ Fix — check case
from pandas import DataFrame # Capital D and F
# ❌ Circular imports
# file a.py:
# from b import B
# file b.py:
# from a import A # Circular!
# ✅ Fix — restructure or use local imports
# In a.py:
def use_b():
from b import B # Import inside function, not at module level
return B()
# ❌ Wrong relative import
from .models import User # This only works inside a package!
# ✅ Fix — use absolute import when running as script
from mypackage.models import UserValueError
KeyError
IndexError
FileNotFoundError
# ❌ FileNotFoundError: No such file or directory
with open("data.csv") as f:
content = f.read()
# ✅ Fix — check if file exists
from pathlib import Path
file_path = Path("data.csv")
if file_path.exists():
with open(file_path) as f:
content = f.read()
else:
print(f"File not found: {file_path}")
# Or use try/except
try:
with open("data.csv") as f:
content = f.read()
except FileNotFoundError:
print("data.csv not found!")
content = ""Exception Handling Best Practices
Quick Error Reference
| Error | Typical Cause | Quick Fix |
|---|---|---|
SyntaxError | Missing colon, bracket, quote | Check syntax carefully |
IndentationError | Wrong indentation | Use 4 spaces consistently |
NameError | Variable not defined | Check spelling, define before use |
TypeError | Wrong type in operation | Convert types, check .get() for None |
AttributeError | Wrong method/attribute name | Check docs, look for typos |
ImportError | Module not installed | pip install module_name |
ValueError | Wrong value for operation | Validate input |
KeyError | Key missing from dict | Use .get() with default |
IndexError | Index out of range | Check len(), use negative indexing |
FileNotFoundError | File doesn't exist | Check path, use Path.exists() |
ZeroDivisionError | Division by zero | Check divisor before dividing |
RecursionError | Infinite recursion | Add base case, increase sys.setrecursionlimit |
*Next: Debugging Techniques →*
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Common Python Errors and Solutions.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, resources, common, errors
Related Python Master Course Topics