Common Python Errors & How to Fix Them
Learn the most common Python errors — SyntaxError, NameError, TypeError, IndexError, KeyError, AttributeError — and how to fix each one.
15 min•By Priygop Team•Updated 2026
Common Errors
Common Errors
# 1. SyntaxError — invalid Python syntax
# if x == 5 # missing colon!
# print "hello" # Python 3 needs parentheses
# 2. NameError — using undefined variable
try:
print(undefined_var)
except NameError as e:
print(f"NameError: {e}")
# 3. TypeError — wrong type for operation
try:
result = "5" + 3
except TypeError as e:
print(f"TypeError: {e}")
print("Fix: result = int('5') + 3")
# 4. IndexError — index out of range
try:
items = [1, 2, 3]
print(items[10])
except IndexError as e:
print(f"IndexError: {e}")
print("Fix: check len(items) first")
# 5. KeyError — missing dictionary key
try:
data = {"name": "Alice"}
print(data["age"])
except KeyError as e:
print(f"KeyError: {e}")
print("Fix: use data.get('age', 'default')")
# 6. AttributeError — missing attribute/method
try:
x = 42
x.append(5)
except AttributeError as e:
print(f"AttributeError: {e}")
print("Fix: x is int, not a list")
# 7. ValueError — right type, wrong value
try:
num = int("hello")
except ValueError as e:
print(f"ValueError: {e}")
# 8. IndentationError
print("\nIndentation: always use 4 spaces!")
# Debugging checklist:
print("\n=== Debugging Checklist ===")
tips = ["Read the error message carefully", "Check the line number",
"print() variables before the error", "Check types with type()",
"Google the error message", "Use breakpoint() to step through"]
for i, tip in enumerate(tips, 1):
print(f" {i}. {tip}")Tip
Tip
Read error messages bottom to top. The last line tells you the error type. Work up the traceback to find where it started.
Diagram
Loading diagram…
Catch specific exceptions. Use else for success logic. finally for cleanup. Custom exceptions for your domain.
Common Mistake
Warning
Ignoring traceback details. The file name, line number, and error message are all you need to find the bug 90% of the time.
Quick Quiz
Practice Task
Note
(1) Intentionally cause a NameError, TypeError, IndexError. (2) Read each traceback. (3) Fix each error based on the message.