Debugging is a Skill โ€” Not a Punishment

Every programmer writes bugs. The difference between a beginner and an intermediate programmer is how quickly they find and fix them. This guide teaches the systematic approach.

Step 1: Read the Error Message Carefully

Python error messages contain 3 pieces of information:

  1. The file and line where the error happened
  2. The type of error (SyntaxError, NameError, etc.)
  3. A description of what went wrong
  File "main.py", line 3, in 
    total = n + 10
TypeError: unsupported operand type(s) for +: 'str' and 'int'

Translation: "On line 3, you tried to add a string and an integer โ€” that doesn't work."

The 7 Most Common Python Errors

1. SyntaxError

if x == 5
    print("five")
# SyntaxError: expected ':'

Fix: Add the missing colon after the condition.

2. IndentationError

if x == 5:
print("five")
# IndentationError: expected an indented block

Fix: Indent the inner block by 4 spaces.

3. NameError

print(my_variable)
# NameError: name 'my_variable' is not defined

Fix: Define the variable before using it. Check for typos.

4. TypeError

"hello" + 5
# TypeError: can only concatenate str to str

Fix: Convert with str(5) or int("5").

5. IndexError

lst = [1, 2, 3]
print(lst[5])
# IndexError: list index out of range

Fix: Check length with len(lst) first.

6. KeyError

d = {"a": 1}
print(d["b"])
# KeyError: 'b'

Fix: Use d.get("b") for safe access.

7. ZeroDivisionError

print(10 / 0)
# ZeroDivisionError: division by zero

Fix: Check for zero before dividing.

Print Debugging: The Simplest Technique

Add print() statements to see what your code is doing:

def calculate_total(items):
    total = 0
    for item in items:
        print(f"DEBUG: item = {item}, total before = {total}")
        total += item
        print(f"DEBUG: total after = {total}")
    return total

calculate_total([1, 2, 3])

In Python 3.8+, use the = trick in f-strings:

print(f"{total=}, {item=}")
# total=0, item=1

The Systematic Debugging Process

  1. Reproduce the bug reliably. Can you make it happen every time?
  2. Isolate the problem. Comment out code until the bug disappears โ€” the last line you commented out is near the problem.
  3. Hypothesise. What do you think is wrong?
  4. Test. Add print statements to verify your hypothesis.
  5. Fix. Make the smallest change possible.
  6. Verify. Run the original scenario and edge cases.

Rubber Duck Debugging

Explain your code line-by-line to an imaginary rubber duck (or your cat, or your friend). Often you'll realise the bug while explaining. Seriously โ€” this works.

When You're Truly Stuck

Practise Debugging in PyForm

PyForm shows error messages clearly and highlights the problem line. Perfect environment for learning to debug.

Try PyForm โ†’