Skip to content

Chapter 13: Common Errors and Debugging

Top 10 Common Errors

bash
# ❌ Error 1: IndentationError — incorrect indentation
# if True:
# print("hello")  # Should be indented!

# ✅ Correct:
if True:
    print("hello")

# ❌ Error 2: NameError — using undefined variables
# print(username)  # username is not defined

# ✅ Correct:
username = "Xiao Ming"
print(username)

# ❌ Error 3: TypeError — type mismatch
# result = "Age: " + 18  # Cannot concatenate string and number directly

# ✅ Correct:
result = "Age: " + str(18)
print(result)

# ❌ Error 4: IndexError — index out of range
# lst = [1, 2, 3]
# print(lst[10])  # Only 3 elements, max index is 2

# ✅ Correct:
lst = [1, 2, 3]
print(lst[2])  # Last valid index

# ❌ Error 5: KeyError — dictionary key not found
# d = {"name": "Xiao Ming"}
# print(d["age"])  # No "age" key exists

# ✅ Correct:
d = {"name": "Xiao Ming"}
print(d.get("age", "Unknown"))
bash
hello
Xiao Ming
Age: 18
3
Unknown
bash
# ❌ Error 6: AttributeError — object has no such attribute
# num = 42
# num.append(1)  # integers don't have an append method

# ✅ Correct:
num = [42]
num.append(1)
print(num)

# ❌ Error 7: ValueError — invalid value
# num = int("hello")  # Cannot convert "hello" to integer

# ✅ Correct:
num = int("42")
print(num)

# ❌ Error 8: SyntaxError — syntax error
# if True       # Missing colon
#     print("hi")

# ✅ Correct:
if True:
    print("hi")

# ❌ Error 9: ModuleNotFoundError — module not found
# import nonexistent_module

# ✅ Correct: pip install first, then import
import json
print("json module loaded")

# ❌ Error 10: FileNotFoundError — file not found
# f = open("nonexistent.txt")

# ✅ Correct: check if file exists first
import os
if os.path.exists("hello.txt"):
    with open("hello.txt") as f:
        print(f.read())
else:
    print("File not found")
bash
[42, 1]
42
hi
json module loaded
File not found

Debugging Techniques

bash
# Technique 1: print debugging (most basic but effective)
def calculate(data):
    print(f"DEBUG: input data = {data}")  # Temporary debug output
    result = sum(data) / len(data)
    print(f"DEBUG: result = {result}")
    return result

calculate([10, 20, 30])

# Technique 2: Using assert statements
def divide(a, b):
    assert b != 0, "Divisor cannot be zero!"
    return a / b

print(divide(10, 2))

# Technique 3: Using the pdb debugger
# Insert breakpoint() in your code to start interactive debugging
# breakpoint()  # Uncomment to use

# Technique 4: Using logging instead of print
import logging
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s")
logging.debug("debug message")
logging.info("info message")
logging.warning("warning message")
logging.error("error message")
bash
DEBUG: input data = [10, 20, 30]
DEBUG: result = 20.0
5.0
DEBUG: debug message
INFO: info message
WARNING: warning message
ERROR: error message

💡 Tip: 💡 Debugging tips: Read the error message — Python's Traceback already tells you which line has what problemRead from bottom to top — the last line is the error type and description, look upward for the offending line numberNarrow it down — comment out parts of the code, use binary search to locate the bugGoogle is your friend — copy the error message and search; 99% of problems have been encountered by someone else