15 Most Common Python Errors & How to Fix Them: Ultimate Debugging Guide (2026)
Every Python developer โ whether a beginner writing their first for loop or a senior backend engineer building AI microservices โ encounters code errors. The difference between a frustrated learner and a high-velocity developer is not that seniors don't make mistakes; it is that seniors know how to read Python tracebacks and fix bugs systematically.
In this ultimate guide, we analyze the 15 most common Python errors that developers encounter every day. We provide real broken code snippets, explain the exact root cause, give clean fixed solutions, and link directly to interactive PyDebug practice challenges where you can test your skills live in your browser.
๐ Table of Contents
- 1. SyntaxError
- 2. IndentationError
- 3. TypeError
- 4. NameError
- 5. IndexError
- 6. KeyError
- 7. ValueError
- 8. AttributeError
- 9. ZeroDivisionError
- 10. UnboundLocalError
- 11. RecursionError
- 12. ModuleNotFoundError
- 13. TypeError on None
- 14. Mutable Default Argument Trap
- 15. FileNotFoundError
- ๐ก 5-Step Debugging Loop
- โ Frequently Asked Questions
1. SyntaxError: Invalid Syntax
What it means: A SyntaxError means Python's parser encountered code that violates the grammatical rules of the language. It happens before your code actually executes.
Common Causes: Missing colons : after if, for, while, or def statements; unmatched parentheses or brackets; or unclosed quotation marks.
def check_even(number)
if number % 2 == 0
print("Even")
def check_even(number):
if number % 2 == 0:
print("Even")
Pro Tip: Look at the line immediately above the arrow ^ in the traceback โ SyntaxErrors are frequently caused by an unclosed parenthesis on the previous line!
2. IndentationError: unexpected indent / expected an indented block
What it means: Python uses whitespace (indentation) to define code blocks instead of curly braces {}. Mixing spaces and tabs or having inconsistent indentation triggers an IndentationError.
def greet(name):
print(f"Hello, {name}") # Missing indent!
def greet(name):
print(f"Hello, {name}") # Standard 4 spaces
3. TypeError: unsupported operand type(s)
What it means: A TypeError occurs when an operation or function is applied to an object of an inappropriate data type.
Example: Combining a string with an integer using the + operator.
age = 25
message = "I am " + age + " years old"
age = 25
message = f"I am {age} years old"
4. NameError: name 'x' is not defined
What it means: Python encountered an identifier (variable or function name) that hasn't been declared in the current local or global scope yet.
print(total_score) # Used before assignment
total_score = 100
total_score = 100
print(total_score) # Defined first
5. IndexError: list index out of range
What it means: You tried to access an element of a sequence (like a list or tuple) at an index that doesn't exist.
Remember: Python lists are zero-indexed! A list with 3 elements has valid indexes 0, 1, and 2.
fruits = ["apple", "banana", "cherry"]
last_fruit = fruits[3] # Index 3 does not exist!
fruits = ["apple", "banana", "cherry"]
last_fruit = fruits[-1] # Gets last element safely
6. KeyError: 'key_name'
What it means: You attempted to look up a key in a dictionary using square brackets dict['key'], but the key was not found in the dictionary.
user = {"username": "coder123"}
email = user["email"] # Crashes with KeyError!
user = {"username": "coder123"}
email = user.get("email", "no-email@provided.com")
7. ValueError: invalid literal for int() with base 10
What it means: A function receives an argument of the correct data type (e.g., string), but the value itself is invalid for the operation (e.g., trying to parse int("hello")).
user_input = "twenty"
age = int(user_input) # Crashes
user_input = "twenty"
try:
age = int(user_input)
except ValueError:
age = 0 # Fallback value
8. AttributeError: 'str' object has no attribute 'append'
What it means: You tried to call a method or access a property on an object that doesn't support it โ often because a variable turned out to be a string or None instead of a list or custom object.
text = "1, 2, 3"
text.append("4") # 'str' has no append method!
numbers = [1, 2, 3] # Make it a list
numbers.append(4) # Works as expected
9. ZeroDivisionError: division by zero
What it means: The second argument of a division / or modulo % operation is zero.
scores = []
average = sum(scores) / len(scores) # len is 0!
scores = []
average = sum(scores) / len(scores) if scores else 0.0
10. UnboundLocalError: local variable referenced before assignment
What it means: Python treats any variable assigned inside a function as local. If you try to read that variable before the assignment line executes inside the function, Python throws an UnboundLocalError.
count = 0
def increment():
count = count + 1 # UnboundLocalError!
increment()
count = 0
def increment(val):
return val + 1
count = increment(count)
11. RecursionError: maximum recursion depth exceeded
What it means: A recursive function kept calling itself without hitting a base case, overflowing Python's call stack (default limit is 1000 frames).
12. ModuleNotFoundError: No module named 'requests'
What it means: Python cannot locate the third-party library or local file you are trying to import. Either it isn't installed via pip or your file name shadows a built-in module name (e.g., naming a local file random.py).
13. TypeError: 'NoneType' object is not subscriptable
What it means: A function returned None (because it lacked an explicit return statement), and later code attempted to index result[0] or iterate over it.
14. The Mutable Default Argument Trap
What it means: Default argument expressions in Python functions are evaluated once when the function is defined, NOT each time it is called. Using a mutable default (like [] or {}) shares state across calls!
def add_item(item, items=[]):
items.append(item)
return items
print(add_item(1)) # [1]
print(add_item(2)) # [1, 2] โ Unexpected!
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(add_item(1)) # [1]
print(add_item(2)) # [2] โ Correct!
15. FileNotFoundError: [Errno 2] No such file or directory
What it means: You attempted to open a file with open('data.csv'), but the file path does not exist relative to the current working directory.
๐ก The 5-Step Professional Python Debugging Loop
When professional developers encounter a bug, they don't guess randomly or rewrite their entire codebase. They execute a repeatable 5-step loop:
- Reproduce reliably: Find the smallest possible input that consistently triggers the error.
- Read the traceback bottom-up: Start at the last line of the error message to identify the exception type, then read the stack trace frame to pinpoint your file and line number.
- Isolate with bisection: Comment out half the suspect function or insert print/breakpoint checks to narrow down where the bad state originates.
- Fix the cause, not the symptom: Never wrap broken logic in a blanket
try...except pass; address why the invalid value was created in the first place. - Verify with edge cases: Test empty lists, zero values, and negative inputs to ensure your fix doesn't introduce regression bugs.
โ Frequently Asked Questions (FAQ)
- Q1: How can I practice Python bug fixing online for free?
- You can practice Python bug fixing directly on PyDebug Problems. It offers hundreds of interactive coding challenges running Pyodide WebAssembly in your browser โ no local setup required.
- Q2: What is the difference between Syntax Errors and Runtime Errors?
- Syntax Errors occur before code execution when Python's parser fails to interpret the code structure. Runtime Errors occur while the program is actively running when invalid operations (like dividing by zero or indexing past list bounds) occur.
- Q3: How do I step through Python code line-by-line?
- You can use Python's built-in debugger by placing
breakpoint()orimport pdb; pdb.set_trace()in your code, or test logic interactively in the PyDebug Playground.