← Back to PyDebug

Python Debugging

πŸ” What Is Debugging?

Debugging is the process of finding and fixing errors (bugs) in your code. Every developer spends a lot of time debugging β€” so it's a critical skill.

1. Read the Error Message Carefully

The error traceback shows the file, line number, and type of error. Start there.

2. The "Print Debugging" Method

Insert temporary print() statements to check variable values and flow.

def calculate(a, b):
    print(f"a={a}, b={b}")   # debug
    result = a / b
    print(f"result={result}") # debug
    return result

3. Using a Debugger (pdb / IDE)

Python's built‑in pdb lets you step through code line by line.

import pdb; pdb.set_trace()   # pauses execution

In our Playground, you can use print statements; for heavier debugging, try an IDE like VS Code.

4. Check Your Assumptions

Often bugs happen because we assume a variable has a certain value, but it doesn't. Verify each step.

5. Simplify the Problem

Comment out parts of code to isolate the bug. Build back step by step.

6. Common Debugging Scenarios

  • Off‑by‑one errors: loops running one too many/few times.
  • Mutable default arguments: using a list as default argument without caution.
  • Scope confusion: variable defined outside function but used inside.

7. Use Version Control (Git)

If you break something, you can revert. Always commit working code before big changes.

πŸ§ͺ Debugging as a Process: The Six-Step Loop

Experienced developers do not "guess until it works" β€” they run a boring, repeatable loop. Write it down; it transfers to every language:

  1. Reproduce. Find the smallest set of steps that triggers the bug every time. A bug you cannot reproduce cannot be fixed reliably.
  2. Read, don't skim. Read the traceback bottom-up and the suspect lines word by word. Most bugs hide in code you have already looked at ten times and stopped seeing.
  3. State the assumption you distrust. Finish the sentence "I assume count is > 0 here because…". Then verify that one assumption with a print or the debugger. Bugs almost always live in a violated assumption.
  4. Bisect. Cut the program in half β€” comment out or return early β€” and see whether the bug survives. Each check halves the suspect region; ten lines of dead code cost more guessing than a minute of bisection.
  5. Fix the cause, not the symptom. Wrapping everything in try/except pass silences the error and keeps the bug. Ask why the bad value existed.
  6. Prove the fix. Re-run the reproduction steps, then run the cases that worked before. A fix without a regression check is an unverified change.

πŸͺ€ Classic Python Bugs Every Learner Should Collect

The mutable default argument

def add(item, bucket=[]):     # the list is created ONCE, at definition time
    bucket.append(item)
    return bucket

print(add(1))   # [1]
print(add(2))   # [1, 2] ← shared state! Fix: bucket=None, then "if bucket is None: bucket = []"

Off-by-one from range and slices disagreeing

nums = [10, 20, 30, 40]
for i in range(1, len(nums)):   # starts at 1 β€” silently skips index 0
    print(nums[i] - nums[i - 1])

Both range(1, 4) and nums[1:4] exclude the end β€” which is exactly why an index written for one convention is off by one in the other.

is vs ==

a = 1000; b = 1000
a == b   # True β€” same value
a is b   # object identity β€” don't rely on it for numbers; use == (and "is" only for None)

Loop variable after the loop

for i in range(5):
    pass
print(i)   # 4 β€” the variable survives the loop; not an error, but a surprise that leaks stale state into later code

πŸ–₯️ pdb Cheat-Sheet (When Prints Aren't Enough)

Once programs get long, line-by-line stepping beats printing: import pdb; pdb.set_trace() (or just breakpoint()) pauses execution, and then n runs the next line, s steps into a call, c continues, p x prints an expression, l shows nearby source, q quits. In the browser-side PyDebug Playground the same discipline applies in miniature: check state just before the crash line, one question at a time.

πŸ¦† Rubber-Duck Debugging, Done Properly

Talking through code works because speaking forces you to state each step in order β€” in your head you skim, aloud you can't. Make it a template, in writing: expected behaviour, actual behaviour, the exact steps to reproduce, and the last thing that changed. The same four-part format is what a good bug report on the community discussion pages needs, and it's roughly what interviewers want to hear when they hand you broken code: not instant knowledge, but a calm process they would trust on their own team.

πŸ”Ž Worked Example: Fixing One Bug Out Loud

Here is the six-step loop applied to a real beginner bug β€” read it as a script to imitate. The code should total a list, but prints a wrong number:

prices = [4.99, 9.99, 2.50]
total = 0
for i in range(1, len(prices)):
    total += prices[i]
print(round(total, 2))

1. Reproduce: any run gives 12.49. 2. Read: no traceback β€” wrong output, so the bug is logic, not syntax. 3. State assumptions: "I assume the loop visits every item" β€” test it with print(i): it prints 1, 2. There it is: index 0 never entered. 4. Bisect: not needed; the suspect region was already the loop header. 5. Fix the cause: range(len(prices)), not range(1, len(prices)) β€” a symptom-patch like adding prices[0] afterwards would break on other lists. 6. Prove: re-run the example (17.48 βœ“), then an empty list (0 βœ“) and a one-item list (4.99 βœ“). Three tests, one minute, done.

Notice what did not happen: no random edits, no rewriting the function from scratch, no googling. The crash never came β€” the method found what the error messages didn't. Wrong-output bugs like this are half of the PyDebug bug set; the prediction guide covers reading the logic before the fix, and the errors guide covers the crash-shaped half.

πŸ”— Keep Going

  • PyDebug Blog β€” expert guides, articles, and bug-fixing strategies.
  • 15 Common Python Errors Guide β€” root causes and exact fixes for top Python bugs.
  • Python Output Prediction Tricks β€” master tricky interview questions.
  • Common Python errors β€” the messages you will actually meet.
  • Python tutorials β€” learn core concepts step by step.