Python Errors & Exceptions Guide
Common errors, what causes them, and how to fix them
SyntaxError Very Common
What it means: Python cannot understand your code because it violates Python's grammar rules. This is caught before the code runs.
Common Causes:
# Missing colon
if x > 5
print("Hello")
# Mismatched parentheses
print("Hello"
# Invalid assignment
5 = x
# Missing quotes
print(Hello World)
How to Fix:
# Add missing colon
if x > 5:
print("Hello")
# Close parentheses
print("Hello")
# Correct assignment
x = 5
# Add quotes
print("Hello World")
NameError Very Common
What it means: You're trying to use a variable or function that hasn't been defined yet.
# Using undefined variable
print(message)
# Typo in variable name
name = "John"
print(nme) # Typo!
# Using variable before assignment
print(total)
total = 100
How to Fix:
# Define before using
message = "Hello"
print(message)
# Check spelling
name = "John"
print(name)
# Assign before using
total = 100
print(total)
TypeError Very Common
What it means: An operation is applied to an object of inappropriate type.
# Adding string and integer
result = "Age: " + 25
# Wrong number of arguments
def greet(name):
print(f"Hello {name}")
greet() # Missing argument
# Calling non-callable
x = 5
x() # Trying to call an integer
# Concatenating incompatible types
lst = [1, 2] + "hello"
How to Fix:
# Convert to string
result = "Age: " + str(25)
# Or use f-string
result = f"Age: {25}"
# Provide required arguments
greet("John")
# Don't call non-functions
x = 5
print(x)
# Use correct types
lst = [1, 2] + list("hello")
IndexError Very Common
What it means: You're trying to access a list/tuple index that doesn't exist.
# Index out of range
fruits = ["apple", "banana", "cherry"]
print(fruits[5]) # Only indices 0, 1, 2 exist
# Empty list access
empty = []
print(empty[0])
# Off-by-one error
for i in range(len(fruits) + 1):
print(fruits[i]) # Fails at last iteration
How to Fix:
# Check length first
fruits = ["apple", "banana", "cherry"]
if len(fruits) > 5:
print(fruits[5])
# Check if list is not empty
if empty:
print(empty[0])
# Use correct range
for i in range(len(fruits)):
print(fruits[i])
# Or iterate directly
for fruit in fruits:
print(fruit)
KeyError Very Common
What it means: You're trying to access a dictionary key that doesn't exist.
# Non-existent key
person = {"name": "John", "age": 30}
print(person["address"])
# Typo in key name
print(person["Name"]) # Keys are case-sensitive
How to Fix:
# Use get() method (returns None if missing)
print(person.get("address"))
# Use get() with default value
print(person.get("address", "Not provided"))
# Check if key exists
if "address" in person:
print(person["address"])
# Use try-except
try:
print(person["address"])
except KeyError:
print("Key not found")
ValueError Very Common
What it means: A function receives an argument of correct type but inappropriate value.
# Invalid conversion
number = int("hello")
# Invalid number format
number = int("12.5") # Use float() first
# Value not in list
fruits = ["apple", "banana"]
fruits.remove("cherry")
# Invalid base conversion
int("xyz", 16)
How to Fix:
# Validate input before conversion
user_input = "hello"
if user_input.isdigit():
number = int(user_input)
# Use try-except
try:
number = int(user_input)
except ValueError:
print("Invalid number")
# Check before removing
if "cherry" in fruits:
fruits.remove("cherry")
AttributeError Common
What it means: You're trying to access an attribute or method that doesn't exist for that object.
# Method doesn't exist for type
name = "John"
name.append("!") # Strings don't have append()
# Typo in method name
fruits = ["apple", "banana"]
fruits.apend("cherry") # Typo!
# None has no attributes
result = None
print(result.upper())
How to Fix:
# Use correct method for type
name = "John"
name = name + "!" # Concatenation for strings
# Check spelling
fruits.append("cherry")
# Check for None first
if result is not None:
print(result.upper())
# Use dir() to see available methods
print(dir(name))
IndentationError Very Common
What it means: Your code's indentation is incorrect. Python uses indentation to define code blocks.
# Missing indentation
if True:
print("Hello")
# Inconsistent indentation
def greet():
print("Hello")
print("World") # Mixed spaces
# Unexpected indent
x = 5
y = 10 # No reason to indent
How to Fix:
# Add proper indentation (4 spaces)
if True:
print("Hello")
# Use consistent indentation
def greet():
print("Hello")
print("World")
# Remove unexpected indentation
x = 5
y = 10
# Tip: Configure editor to use 4 spaces for tabs
ZeroDivisionError Common
What it means: You're trying to divide a number by zero, which is mathematically undefined.
# Direct division by zero
result = 10 / 0
# Division with variable
divisor = 0
result = 100 / divisor
# Modulo by zero
result = 10 % 0
How to Fix:
# Check before dividing
divisor = 0
if divisor != 0:
result = 100 / divisor
else:
result = 0 # Or handle appropriately
# Use try-except
try:
result = 10 / divisor
except ZeroDivisionError:
print("Cannot divide by zero")
result = None
FileNotFoundError Common
What it means: Python cannot find the file you're trying to open.
# File doesn't exist
with open("nonexistent.txt", "r") as f:
data = f.read()
# Wrong path
with open("data/file.txt", "r") as f:
data = f.read()
# Typo in filename
with open("daat.txt", "r") as f: # Should be data.txt
data = f.read()
How to Fix:
import os
# Check if file exists first
if os.path.exists("data.txt"):
with open("data.txt", "r") as f:
data = f.read()
# Use try-except
try:
with open("data.txt", "r") as f:
data = f.read()
except FileNotFoundError:
print("File not found!")
data = ""
# Use absolute path
with open(r"C:\Users\name\data.txt", "r") as f:
data = f.read()
ImportError / ModuleNotFoundError Common
What it means: Python cannot find or import the module you're trying to use.
# Module not installed
import pandas
# Typo in module name
import numpyy
# Wrong import path
from mypackage import mymodule
# Circular import
# file1.py: from file2 import func2
# file2.py: from file1 import func1
How to Fix:
# Install the module first
# pip install pandas
# Check spelling
import numpy
# Verify module is installed
try:
import pandas
except ImportError:
print("Please install: pip install pandas")
# Check your PYTHONPATH for custom modules
RecursionError Less Common
What it means: A function calls itself too many times (infinite recursion) and exceeds Python's recursion limit.
# Missing base case
def factorial(n):
return n * factorial(n - 1) # Never stops!
factorial(5)
# Incorrect base case
def countdown(n):
print(n)
countdown(n - 1) # No stopping condition
How to Fix:
# Add proper base case
def factorial(n):
if n <= 1: # Base case!
return 1
return n * factorial(n - 1)
# Add stopping condition
def countdown(n):
if n <= 0: # Base case!
return
print(n)
countdown(n - 1)
# Or use iteration instead
def factorial_iter(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
Quick Debugging Tips
1. Read the error message
The last line tells you the error type and description.
2. Check the line number
The traceback shows exactly where the error occurred.
3. Use print() debugging
Print variable values before the error line.
4. Use try-except
Wrap risky code in try-except blocks.