Skip to main content

Programming fundamentals · Beginner · 17 min

Find a bug step by step: reproduce, isolate, fix and check

By Padding · Updated 18 Nov 2026
Python 3.15.2 · python:3.15-slim (Debian)

You will track down a wrong total in a short Python script by reproducing it, shrinking the input, testing one hypothesis at a time, fixing it, adding a test and writing a bug report.

On this page

Some bugs crash with a traceback that points at the line. The harder ones do not crash at all: the program runs, prints a number, and the number is wrong. Staring at the code and changing things until the answer looks right rarely works, and when it does you do not know why. A routine works better, and it is the same routine in every language.

In this tutorial you are handed a short Python script that totals a shopping basket and applies a bulk discount. For some baskets the total is wrong. You find out why by following five moves in order:

  1. Reproduce the bug with a fixed input, and write down what you expected.
  2. Shrink the input until it is as small as it can be while the bug still shows.
  3. Form one hypothesis at a time, after explaining the code aloud.
  4. Test the hypothesis with a print or an assert, then fix the cause.
  5. Check the fix with a test so the bug stays fixed, and write it up.

The examples use python3. On Windows outside WSL, type py instead. Prices are in no particular currency, so read them as naira, cedis, shillings, rand or whatever you use. Everything runs offline, so once Python is installed it costs no mobile data.

Step 1 · Run the script and see the wrong total

Make a folder for this tutorial and create the script exactly as you received it, bug included:

Bash
mkdir -p ~/bug-hunt-demo
cd ~/bug-hunt-demo
cat > basket.py <<'PY'
import sys
from pathlib import Path

BULK_QTY = 10
BULK_DISCOUNT = 0.10


def parse_line(line):
    name, qty, price = line.split(",")
    return name.strip(), int(qty), float(price)


def basket_total(lines):
    total = 0
    rate = 1.0
    for line in lines:
        name, qty, price = parse_line(line)
        if qty >= BULK_QTY:
            rate = rate - BULK_DISCOUNT
        total = total + qty * price * rate
    return round(total, 2)


def main():
    text = Path(sys.argv[1]).read_text(encoding="utf-8")
    lines = [line for line in text.splitlines() if line.strip()]
    print(f"Total: {basket_total(lines):.2f}")


if __name__ == "__main__":
    main()
PY

What it does, function by function:

  • parse_line takes one line such as rice, 2, 1500, splits it on commas and returns the name, the quantity as a whole number and the unit price as a decimal.
  • basket_total walks through the lines and adds quantity × price × rate to a running total. The rule it is meant to apply: any line with 10 or more of an item gets 10% off that line.
  • main reads the file named on the command line, skips blank lines and prints the total with two decimal places.
  • if __name__ == "__main__": runs main only when you start the file directly. Later you import basket_total from a test file, and this line stops the import from running main too.

Now create the basket a customer complained about:

Bash
cat > basket.txt <<'TXT'
rice, 2, 1500
eggs, 30, 120
bread, 1, 900
milk, 3, 650
tomatoes, 12, 200
oil, 1, 3200
TXT
python3 basket.py basket.txt

Check it worked

The script prints Total: 13285.00. Nothing crashes, which is exactly what makes this kind of bug easy to miss.

Step 2 · Reproduce the bug with a fixed input

A bug you cannot make happen on demand is a bug you cannot prove you fixed. So the first job is a fixed input, a fixed command, and a written expected answer to compare against.

Work out the right total by hand, one line at a time, applying the rule as stated (10 or more of an item gets 10% off that line):

  • rice: 2 × 1500 = 3000
  • eggs: 30 × 120 = 3600, less 10% = 3240
  • bread: 1 × 900 = 900
  • milk: 3 × 650 = 1950
  • tomatoes: 12 × 200 = 2400, less 10% = 2160
  • oil: 1 × 3200 = 3200

The lines add up to 14450. Start a bug log, a plain text file where you note what you try and what you see. It feels slow, and it saves you from testing the same idea twice:

Bash
cat > bug-log.txt <<'TXT'
Command:  python3 basket.py basket.txt
Expected: Total: 14450.00 (worked out by hand)
Actual:   Total: 13285.00
TXT
python3 basket.py basket.txt
python3 basket.py basket.txt

Running it twice shows the bug is steady. If the number changed between runs, you would be looking for something that varies (the time, random numbers, a file another program writes), and that is a different hunt.

Check it worked

Both runs print Total: 13285.00, and cat bug-log.txt shows the command, the expected total and the actual total. The difference is 1165, which you can note in the log too.

Step 3 · Shrink the input until the bug still shows

Six lines is already small, but every line you remove is one less thing that could be involved. Remove lines and keep the smallest basket that is still wrong. Start with each line on its own. The printf command writes one line to a file, and \n ends the line:

Bash
printf 'eggs, 30, 120\n' > one.txt
python3 basket.py one.txt
printf 'bread, 1, 900\n' > one.txt
python3 basket.py one.txt

Eggs alone gives Total: 3240.00 and bread alone gives Total: 900.00. Both are right, so a single line is never enough to cause it, and the discount itself works. Try pairs. The first discounted line in the basket is eggs, so pair it with the line after it:

Bash
printf 'eggs, 30, 120\nbread, 1, 900\n' > small.txt
python3 basket.py small.txt
printf 'bread, 1, 900\neggs, 30, 120\n' > swapped.txt
python3 basket.py swapped.txt

The right answer for both files is 3240 + 900 = 4140.

Check it worked

small.txt (eggs, then bread) prints Total: 4050.00, which is wrong by 90. swapped.txt (bread, then eggs) prints Total: 4140.00, which is right. Add both results to bug-log.txt.

This is the most useful clue so far: the same two items give different totals depending on their order, and the error, 90, is exactly 10% of the bread line. A two-line input that you can type from memory is your minimal example.

Step 4 · Explain the code aloud and list hypotheses

Before you change anything, read basket_total out loud, line by line, as if to someone who has never seen it. Programmers call this rubber-duck debugging, after the habit of explaining code to a toy duck on the desk. Saying what each line does, not what you meant it to do, is often enough to spot the problem. With small.txt in mind, it goes something like this:

  • "Set the total to 0 and the rate to 1.0, meaning full price."
  • "First line, eggs: quantity 30 is 10 or more, so take 0.10 off the rate. The rate is now 0.9. Add 30 × 120 × 0.9."
  • "Second line, bread: quantity 1 is less than 10, so skip the if. Add 1 × 900 × the rate, which is... still 0.9."

You may already see it. Even so, write down the possible causes before testing any of them, so you test them one at a time instead of changing three things at once:

Bash
cat >> bug-log.txt <<'TXT'
Minimal example: eggs (30) then bread (1) gives 4050, expected 4140.
Order matters: bread then eggs gives the right 4140.
Hypothesis 1: parse_line reads the bread line wrongly.
Hypothesis 2: the discount rate from eggs carries over to bread.
TXT
cat bug-log.txt

Order the list so the cheapest thing to check comes first. Hypothesis 1 is quick to rule in or out, so it goes first even if you suspect hypothesis 2.

Check it worked

bug-log.txt now holds the expected and actual totals, the minimal example, and two numbered hypotheses, each one a statement that can be shown true or false.

Step 5 · Test one hypothesis at a time

Test hypothesis 1 by calling parse_line directly on the bread line. python3 -c runs the Python code in quotes, and from basket import parse_line loads the function from basket.py without running main:

Bash
python3 -c 'from basket import parse_line; print(parse_line("bread, 1, 900"))'

It prints ('bread', 1, 900.0): the right name, quantity and price. Hypothesis 1 is false. Cross it off in the log and move to hypothesis 2.

To test hypothesis 2 you need to see the rate on every line. Open basket.py in your editor and add one line inside the loop, after the total is updated, marked so you remember to remove it:

Bash
cat > basket.py <<'PY'
import sys
from pathlib import Path

BULK_QTY = 10
BULK_DISCOUNT = 0.10


def parse_line(line):
    name, qty, price = line.split(",")
    return name.strip(), int(qty), float(price)


def basket_total(lines):
    total = 0
    rate = 1.0
    for line in lines:
        name, qty, price = parse_line(line)
        if qty >= BULK_QTY:
            rate = rate - BULK_DISCOUNT
        total = total + qty * price * rate
        print(f"DEBUG {name}: qty={qty} rate={rate}")  # debug: remove
    return round(total, 2)


def main():
    text = Path(sys.argv[1]).read_text(encoding="utf-8")
    lines = [line for line in text.splitlines() if line.strip()]
    print(f"Total: {basket_total(lines):.2f}")


if __name__ == "__main__":
    main()
PY
python3 basket.py small.txt
python3 basket.py basket.txt

For small.txt the output includes DEBUG bread: qty=1 rate=0.9. Bread should be full price, so this confirms hypothesis 2. The full basket shows more: every line after eggs gets 0.9, and tomatoes, the second bulk line, gets rate=0.8, because a second 0.10 came off a rate that was never put back.

A print shows you what happened once. An assert states what must always be true and stops the program the moment it is not. Replace the debug line with an assert that says a line under 10 items must be at full price:

Bash
cat > basket.py <<'PY'
import sys
from pathlib import Path

BULK_QTY = 10
BULK_DISCOUNT = 0.10


def parse_line(line):
    name, qty, price = line.split(",")
    return name.strip(), int(qty), float(price)


def basket_total(lines):
    total = 0
    rate = 1.0
    for line in lines:
        name, qty, price = parse_line(line)
        if qty >= BULK_QTY:
            rate = rate - BULK_DISCOUNT
        if qty < BULK_QTY:
            assert rate == 1.0, f"{name} has rate {rate}"  # debug: remove
        total = total + qty * price * rate
    return round(total, 2)


def main():
    text = Path(sys.argv[1]).read_text(encoding="utf-8")
    lines = [line for line in text.splitlines() if line.strip()]
    print(f"Total: {basket_total(lines):.2f}")


if __name__ == "__main__":
    main()
PY
python3 basket.py small.txt || echo "exit status $?"

assert condition, message does nothing while the condition is true. When it is false, Python raises AssertionError with your message. || echo "exit status $?" prints the exit status when the script fails, so you can see it stopped.

Check it worked

The run ends with a traceback whose last line is AssertionError: bread has rate 0.9, followed by exit status 1. The assert names the exact line and value that broke the rule. Write "Hypothesis 2: confirmed" in the log.

Step 6 · Fix the cause and check every case

The cause is that rate is set once, before the loop, and only ever goes down. The discount belongs to one line, so work out the rate fresh for each line. Replace basket_total with this version and remove both debug lines:

Bash
cat > basket.py <<'PY'
import sys
from pathlib import Path

BULK_QTY = 10
BULK_DISCOUNT = 0.10


def parse_line(line):
    name, qty, price = line.split(",")
    return name.strip(), int(qty), float(price)


def basket_total(lines):
    total = 0
    for line in lines:
        name, qty, price = parse_line(line)
        if qty >= BULK_QTY:
            rate = 1 - BULK_DISCOUNT
        else:
            rate = 1.0
        total = total + qty * price * rate
    return round(total, 2)


def main():
    text = Path(sys.argv[1]).read_text(encoding="utf-8")
    lines = [line for line in text.splitlines() if line.strip()]
    print(f"Total: {basket_total(lines):.2f}")


if __name__ == "__main__":
    main()
PY
python3 basket.py small.txt
python3 basket.py swapped.txt
python3 basket.py basket.txt

Now every pass through the loop sets rate before using it, so nothing can carry over from the line before. Rerun the minimal example first, then the original basket: the fix has to work on the input that started the hunt, not only the small one.

Check it worked

small.txt and swapped.txt both print Total: 4140.00, and basket.txt prints Total: 14450.00, the total you worked out by hand. Run grep -n debug basket.py: it prints nothing, so no debug lines were left behind.

Step 7 · Add a test so the bug stays fixed

Bugs come back. Someone tidies the loop next month and moves rate above it again. A test runs your minimal example automatically and fails loudly if that happens. Python ships with the unittest module, so there is nothing to install:

Bash
cat > test_basket.py <<'PY'
import unittest

from basket import basket_total


class BasketTotalTests(unittest.TestCase):
    def test_line_under_bulk_quantity_is_full_price(self):
        self.assertEqual(basket_total(["bread, 1, 900"]), 900)

    def test_bulk_line_gets_ten_percent_off(self):
        self.assertEqual(basket_total(["eggs, 30, 120"]), 3240)

    def test_discount_does_not_carry_to_next_line(self):
        self.assertEqual(basket_total(["eggs, 30, 120", "bread, 1, 900"]), 4140)

    def test_two_bulk_lines_each_get_ten_percent(self):
        self.assertEqual(basket_total(["eggs, 30, 120", "tomatoes, 12, 200"]), 5400)


if __name__ == "__main__":
    unittest.main()
PY
python3 -m unittest -v

Each method whose name starts with test_ is one test. assertEqual(actual, expected) fails the test if the two values differ and shows both. The third test is your minimal example, word for word, and the fourth covers the second thing the debug print showed you: two bulk lines (3240 + 2160 = 5400). python3 -m unittest finds files named test*.py in the current folder and runs every test in them. -v lists each test by name.

Name tests after the rule they protect, as here, so a failure tells the next person what broke without reading the code.

Check it worked

The output lists four tests, each ending in ok, then Ran 4 tests and OK on the last line. To see the test do its job, move rate = 1.0 back above the loop in your editor and delete the else: branch, run python3 -m unittest again, and watch test_discount_does_not_carry_to_next_line fail. Then put the fix back and confirm all four pass.

Step 8 · Write the bug report, and know when to ask for help

The log you kept is most of a bug report already. Turn it into one that someone else could act on without asking you anything:

Bash
cat > bug-report.txt <<'TXT'
Title: Bulk discount carries over to later lines in basket_total

Steps to reproduce:
  Basket file with two lines:
    eggs, 30, 120
    bread, 1, 900
  Run: python3 basket.py small.txt   (Python 3.15.2)

Expected: Total: 4140.00 (eggs 3240 after 10% off, bread 900)
Actual:   Total: 4050.00 (bread was also given 10% off)

Notes: order matters; bread before eggs gives the right total.
A second bulk line takes the rate down to 0.8.

Cause: rate was set once before the loop and reduced on each bulk
line, never reset.
Fix: work out the rate inside the loop for each line.
Test: test_discount_does_not_carry_to_next_line in test_basket.py.
TXT
cat bug-report.txt
python3 --version

A good report has the smallest input that shows the bug, the exact command, the expected result with the reason, the actual result, and the version you ran. "The total is wrong sometimes" gives the reader nothing to run. If you are reporting a bug before you have found the cause, stop after the notes: the steps, expected and actual are the part that matters.

When to stop and ask. Give yourself a time limit, for example 30 to 60 minutes with no new clue, then ask a colleague or post in a forum. The minimal example is what makes the question answerable: paste the two-line input, the short function and both outputs as text. Text is easier to search, copy and run than a screenshot, and it is far smaller to send, which matters when the person helping you is reading on a phone with prepaid data. Very often, cutting a problem down to a minimal example to ask about it shows you the answer before you post.

Check it worked

cat bug-report.txt shows a title, steps to reproduce with the two-line basket, expected and actual totals, the cause, the fix and the name of the test. python3 --version prints the version you would add to a real report, such as Python 3.15.2.

When you have finished, delete the demo folder:

Bash
cd ~
rm -rf ~/bug-hunt-demo

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.