Skip to content

Module 19 · Debugging, Testing and Best Practices — topic 1 of 15

Debugging

A systematic approach to finding and fixing bugs: reproduce the problem, form hypotheses, gather evidence, isolate the cause, fix it, and confirm with tests — plus the tools Python offers for each step.

Beginner 10 min read·Lesson 279 of 306 in Python Programming

Learning objectives

  • Follow a systematic debugging process
  • Reproduce bugs with small, repeatable inputs
  • Confirm fixes with checks that would have caught the bug

Definition

Debugging is the process of finding the cause of incorrect behaviour in a program and fixing it. Effective debugging is systematic: reproduce, hypothesise, test the hypothesis, fix, and verify.

Introduction

Every programmer spends a large part of their time debugging. The difference between a frustrating afternoon and a ten-minute fix is usually method, not luck.

Why it matters

Systematic debugging finds the real cause instead of patching symptoms, and leaves behind tests that stop the bug from returning.

Detailed explanation

Reproduce the bug reliably first. Note the exact input, steps and the expected versus actual output.

Shrink the input to the smallest case that still fails; small cases are far easier to reason about.

Form a hypothesis about the cause ('the loop skips the first item'), then gather evidence that confirms or rejects it — print values, use a debugger, or write a quick check.

Change one thing at a time so you know which change mattered.

Read error messages and tracebacks carefully; they often point directly at the problem (see Reading tracebacks).

Once fixed, add a test or check that reproduces the original bug, so it can't silently return (a regression test).

Explaining the code line by line to someone else — or to a rubber duck — often reveals the bug.

Take breaks: a fresh look frequently spots what hours of staring missed.

Syntax

Text
# 1. Reproduce with a known input
# 2. Shrink it to a minimal failing case
# 3. Hypothesise and gather evidence
# 4. Fix one thing
# 5. Add a regression check
  • Reproduce first.
  • Test one hypothesis at a time.
  • Leave a check behind.

Code examples

An off-by-one bug

Python
def average_buggy(nums):
total = 0
for i in range(1, len(nums)): # skips index 0
total += nums[i]
return total / len(nums)
def average(nums):
return sum(nums) / len(nums)
data = [10, 20, 30]
print(average_buggy(data), average(data))
Output
16.666666666666668 20.0

Narrowing down with small inputs

Python
def is_valid_username(name):
return name.isalnum() and 3 <= len(name) <= 12
for case in ["asha", "ra", "ravi_k", "meera2026", "averyveryverylongname"]:
print(case, is_valid_username(case))
Output
asha True
ra False
ravi_k False
meera2026 True
averyveryverylongname False

The third case shows the rule rejects underscores — maybe a bug, maybe intended. Small cases make such questions visible.

More examples

Checks that expose and confirm a fix

Python
def final_price_buggy(price, discount_percent):
return price - price * discount_percent
def final_price(price, discount_percent):
return price * (1 - discount_percent / 100)
checks = [(100, 10, 90.0), (250, 0, 250.0), (80, 50, 40.0)]
def failures(fn):
return [(p, d, fn(p, d), expected) for p, d, expected in checks if fn(p, d) != expected]
print("buggy failures:", failures(final_price_buggy))
print("fixed failures:", failures(final_price))
Output
buggy failures: [(100, 10, -900, 90.0), (80, 50, -3920, 40.0)]
fixed failures: []

Step-by-step explanation

  • Each check records an input and the expected result, worked out by hand.
  • The buggy version passes the 0% case but fails the others, pointing at how the percentage is used.
  • After the fix, the same checks pass — and they stay as regression tests.

Expected output

Running “Checks that expose and confirm a fix” prints exactly:

TextOutput
buggy failures: [(100, 10, -900, 90.0), (80, 50, -3920, 40.0)]
fixed failures: []

Practical applications

  • Fixing a bug reported by a user with a screenshot and exact steps.
  • Investigating failing tests in a CI pipeline.

Best practices

  • Reproduce before fixing.
  • Shrink failing inputs.
  • Turn every fixed bug into a test.

Common mistakes

Changing many things at once

Avoid

# rewrite three functions and hope the bug goes away

Prefer

# change one thing, rerun, observe

You won't know which change fixed (or caused) the problem.

Important notes

  • The following lessons cover tracebacks, print debugging, the VS Code debugger and testing tools.

Key takeaways

  • Debugging is systematic: reproduce, hypothesise, test, fix, verify.
  • Small failing inputs make causes clear.
  • Regression checks keep bugs fixed.

Try it yourself

  1. 1
    Find and fix the bug in a function that should count vowels but misses capital letters.
  2. 2
    Write three checks for a temperature-conversion function and use them to find a deliberately introduced bug.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

10 questions cover the “Debugging, Testing and Best Practices” module. Answers and explanations are revealed after you submit.

  • AdvancedWhy shouldn't assert be used to validate user input?
  • AdvancedWhat is printed?
  • AdvancedWhere should you usually start reading a Python traceback?
Practise this module