← All lessons
Python intermediate · Lesson 11 of 11

Testing and debugging

A bug is code that runs but does the wrong thing. Everyone writes them. What separates good programmers is that they find them quickly, and that they write tests so the same bug can't sneak back.

assert checks that something is True and raises AssertionError if it isn't. It's the simplest test: say what the answer should be.

def average(nums):
    return sum(nums) / len(nums)

assert average([2, 4]) == 3
assert average([5]) == 5
print("all good")
Prints
all good

A test is a small function that calls your code with known inputs and asserts the outputs. pytest is the most popular tool for running them: install it with pip install pytest, put tests in files named test_something.py with functions named test_..., and run pytest in the terminal. It finds and runs them all and tells you which failed and why.

# test_shop.py
from shop import add_tax

def test_add_tax():
    assert add_tax(100) == 120

def test_add_tax_zero():
    assert add_tax(0) == 0

Test the edges, not just the easy case: an empty list, zero, a negative number, one item, a very long string. Bugs live at the edges. (Python also has a built-in unittest module that does the same job with classes.)

To debug is to find out why code does what it does. Start by making the bug happen reliably, then narrow down where it starts. The quickest tool is print(): print the values in the middle of the code and see where they stop being what you expect. f-strings have a shortcut, f"{x=}", that prints the name and the value.

def total(prices):
    t = 0
    for p in prices:
        t = p
        print(f"{p=} {t=}")
    return t

total([3, 4])
Prints
p=3 t=3
p=4 t=4

The printout gives it away: t never grows, because the line should be t += p. For bigger problems, a debugger lets you pause the program on a line and look at every variable. Put breakpoint() in the code, or click beside a line number in an editor like VS Code or PyCharm, and step through one line at a time.

Bugs everyone writes

  • Off by one: range(1, 10) stops at 9, items[len(items)] is past the end.
  • = where you meant ==, or comparing a string to a number ("5" == 5 is False).
  • Changing a list while looping over it, which skips items. Loop over a copy (for x in items[:]) or build a new list.
  • The mutable default argument (def f(x=[])) from the functions lesson.
  • Forgetting to return, so the caller gets None.

Explain the code out loud, line by line, to someone or something (programmers famously use a rubber duck). Saying what each line should do is often when you notice it doesn't.

Practice

What does this print?

def biggest(nums):
    best = 0
    for n in nums:
        if n > best:
            best = n
    return best

print(biggest([-5, -2, -9]))
More info

Quick reference

assert condRaises AssertionError if cond is False.
pytestRuns test_*.py files' test_* functions: pip install pytest, then pytest.
f"{x=}"Prints x=value, for quick debugging.
breakpoint()Pauses the program in the debugger at that line.
edge caseAn unusual input (empty, zero, negative, huge) where bugs hide.

Related courses