Module 03 · Lesson 3.2
Hypotheses and Experiments
On this page
- What you will learn
- What a hypothesis is, and why you need several
- Worked scenario: five suspects for the missing penny
- Step-by-step workflow: from ideas to evidence
- Running cheap experiments on the napkin bug
- The hypothesis log: recording what you learned
- Using an AI assistant to brainstorm hypotheses
- Conclusion and your next step
- Reusable prompt
- Expected output
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
A doctor does not order every test for every patient. They list what could explain the symptoms, think about which are likely, and run the quick, cheap tests first. Each result removes some possibilities. Good debugging works the same way.
In this lesson you learn to write down hypotheses, which are explanations you can test. You rank them, design one cheap experiment for each, and keep a hypothesis log so that nothing is forgotten. The example continues the napkin invoice from the last lesson, using the fictional Tidewell Wholesale service and a simplified version of its code.
What you will learn
- Write hypotheses that make a prediction you can check.
- Rank hypotheses by how likely they are and how cheap they are to test.
- Design and run the cheapest experiment that can prove a hypothesis wrong.
- Keep a hypothesis log that records each idea, its experiment and its result.
Before you start
- Finish Reproducing a Failure. You need a failing case that you can run on demand.
- Python 3 and the practice code from that lesson, or a defect you can already reproduce in your own repository.
- Basic comfort with running a script and reading its printed output.
What a hypothesis is, and why you need several
A hypothesis is an explanation that could be true and that you can test. 'The code is broken' is not a hypothesis. 'The code rounds the price down because it uses float numbers' is one, because you can check it.
- Hypothesis
- A possible explanation with a prediction attached: 'If this is the cause, then I will see that.' It is like a detective's theory.
- Experiment
- A small action that checks a prediction, such as printing a value or running the code with one input changed.
- Evidence
- What the experiment showed. Evidence is a recorded fact, not an opinion.
- Ruled out
- A hypothesis whose prediction failed. Ruling things out is real progress, even though it feels like nothing happened.
- Hypothesis log
- A table of every idea you had, what you did to test it, and what you found. It works like a lab notebook.
Why keep several hypotheses? If you only hold one, you will look for proof that it is right and ignore signs that it is wrong. People call this confirmation bias. A list of rivals makes you ask, 'What would tell these apart?'
Worked scenario: five suspects for the missing penny
You have a reproduction. Account TC7-0042 buys NAP-100 napkins at £1.25 with a 10% contract discount. Finance policy says the unit price is £1.125 rounded half up, which is £1.13. The service gives £1.12, so 40 packs cost £44.80 instead of £45.20.
You list every explanation you can think of. For each one you write what you would see if it were true, and how cheap it is to check.
| Rank | Hypothesis | If true, we would see | Cheapest experiment |
|---|---|---|---|
| 1 | The accounts system is the one that is wrong. | Finance's own policy gives £1.12. | Ask the finance systems contact for the rule, then work the sum by hand. |
| 2 | VAT is rounded wrongly. | A small gap that does not grow with quantity. | Compare the gap for 1, 10 and 40 packs. |
| 3 | Rounding per order instead of per line. | A gap that does not grow with quantity. | The same comparison. |
| 4 | A wrong discount is stored for TC7-0042. | Odd results for all products on this account. | Read the stored discount, then try other prices. |
| 5 | Float arithmetic in contract pricing. | Wrong results for some prices and discounts, on any account. | Print the numbers inside the calculation. |
Ranking does not mean 'most likely first'. It means 'what removes the most doubt for the least effort'. Asking finance takes five minutes and could end the whole investigation, so it goes first even though you expect the service to be at fault.
Notice also that one failing case fits several of these ideas. A stored discount of 10.5%, for example, would also give £1.12. Experiments that use other prices will help to tell the ideas apart.
Step-by-step workflow: from ideas to evidence
Step 1: State the question
Write one line: 'Why does NAP-100 at 10% off give 1.12 and not 1.13?' Every hypothesis must answer this question.
What you should see: A single question at the top of your log.
Step 2: List hypotheses without judging them
Write down every explanation, including silly ones and 'the reference is wrong'. Ask a colleague or an assistant for more, then remove duplicates.
What you should see: Five to ten candidate explanations.
Step 3: Attach a prediction to each
Finish the sentence: 'If this is the cause, then ...'. A hypothesis with no prediction cannot be tested.
What you should see: Each idea has an observable consequence.
Step 4: Rank by likelihood and cost
Give each idea a rough chance and a rough cost in minutes. Test cheap ideas first, and test likely ideas early. Never skip an idea because you are sure.
What you should see: A numbered order of experiments.
Step 5: Run one experiment at a time
Predict the result, run it, and write down what happened, even when it is boring. Change only one thing between runs.
What you should see: One result recorded for each experiment.
Step 6: Update the log and the ranking
Mark each idea as ruled out, supported or still open. New evidence often creates new hypotheses. Add them.
What you should see: A log that shows what you know and what you do not.
- Question
Why 1.12, not 1.13?
- Hypotheses
Each with a prediction
- Rank
Likelihood and cost
- Experiment
One change at a time
- Record
Ruled out or supported
- Update
New ideas, new ranking
Repeat until one explanation survives every experiment.
How to design a cheap, useful experiment
- Predict first. Write down what you expect before you run it. If you decide afterwards, any result will seem to fit.
- Change one thing. If you change two, you cannot tell which one mattered.
- Use a referee. Compare the code with a trusted answer, such as a hand calculation or
Decimal. - Look at the middle, not only the end. Print values inside the calculation, as Experiment 2 did.
- Aim to prove yourself wrong. The best experiment is the one that could kill your favourite idea.
| Tool | Use it when | Cost |
|---|---|---|
| A print statement or a small script | You want to see one value or compare two. | Seconds |
The logging module | You need evidence from a run you cannot watch. | Minutes |
The debugger, pdb | You want to stop the program and look around. | Minutes |
| A test | You want a repeatable check that stays in the project. | Minutes to hours |
| Version history | You want to know when behaviour changed. | Minutes |
Python's pdb debugger lets you pause a program at a line and inspect its values. You start it by writing breakpoint() where you want to pause. Its guide is in the references.
Running cheap experiments on the napkin bug
Each experiment below is a tiny script. Run them from the top folder of the practice repository, the same place you ran the reproduction in the last lesson. They use a simplified version of the service's pricing code, so no Django is needed.
Experiment 1: does the gap grow with the quantity?
This tests the VAT idea and the rounding-per-order idea together. The prediction: if the cause is a rounding step applied once to a total, the gap stays tiny whatever the quantity. If the cause is in the unit price, the gap grows with the quantity.
"""Experiment 3: does the gap grow with the quantity?"""
from decimal import Decimal
from invoicing.totals import price_order
PRICES = {"NAP-100": Decimal("1.25")}
for qty in (1, 10, 40):
got = price_order([("NAP-100", qty)], "Contract", PRICES, 10)
expected = Decimal("1.13") * qty
print(f"qty {qty:>2}: got {got}, expected {expected}, gap {expected - got}")qty 1: got 1.12, expected 1.13, gap 0.01
qty 10: got 11.20, expected 11.30, gap 0.10
qty 40: got 44.80, expected 45.20, gap 0.40for qty in (1, 10, 40)tries three order sizes.price_order(...)is the service's pricing function. It gives the total the service charges.Decimal("1.13") * qtyis the total finance expects.- The last line prints the gap between the two.
The gap is 1p, 10p and 40p. It grows with the quantity, exactly 1p per pack. A rounding step on the total could never produce a 40p gap, because rounding to the penny moves a number by half a penny at most. So the VAT idea and the per-order idea are ruled out for this case. The cause sits in the price of a single pack.
Experiment 2: look inside the calculation
Now check the float idea. The service works out the contract price with ordinary decimal-point numbers called floats. The prediction: if float arithmetic is involved, the numbers inside the calculation will show something unexpected.
"""Experiment 1: print the numbers inside the float calculation."""
from decimal import Decimal
list_price = 1.25
factor = 1 - 10 / 100
product = list_price * factor
print("factor :", repr(factor))
print("product :", repr(product))
print("stored exactly :", Decimal(product))
print("round(product, 2):", round(product, 2))factor : 0.9
product : 1.125
stored exactly : 1.125
round(product, 2): 1.12factoris the share of the price the customer pays: 1 minus 10 divided by 100.productis the list price times that share. It is the exact price before rounding.Decimal(product)prints the exact value that the float really stores.round(product, 2)is Python's built-in rounding to two decimal places, which the service uses.
This result is a surprise. The float is not slightly off. It stores exactly 1.125, which is an exact half penny. And round() gives 1.12, not 1.13. So the float is not the whole story. The rounding rule is also involved.
Experiment 3: compare with Decimal and two rounding rules
A Decimal is Python's exact decimal number type. It is a good referee, because it does money sums the way people do on paper. Here you run the same sum with two rules for the exact half.
"""Experiment 2: the same sum in Decimal, with two rounding rules."""
from decimal import Decimal, ROUND_HALF_EVEN, ROUND_HALF_UP
PENNY = Decimal("0.01")
exact = Decimal("1.25") * Decimal("0.90")
print("exact price :", exact)
print("half up to penny :", exact.quantize(PENNY, rounding=ROUND_HALF_UP))
print("half even penny :", exact.quantize(PENNY, rounding=ROUND_HALF_EVEN))exact price : 1.1250
half up to penny : 1.13
half even penny : 1.12ROUND_HALF_UPis the rule most people learn at school: a half goes up. 1.125 becomes 1.13.ROUND_HALF_EVENsends a half to the neighbour whose last digit is even. 1.125 becomes 1.12, because 2 is even and 3 is odd.- Python's built-in
round()follows the 'half to even' rule. People call it banker's rounding. It exists so that, over many roundings, ups and downs cancel out.
Here is the first cause. For an exact half, round() follows the 'half to even' rule, and finance wants 'half up'. That alone explains £1.12 for NAP-100.
Experiment 4: try other prices
One case can fit many ideas. So try several prices and discounts, and print the exact value that each float stores. The prediction: if float arithmetic is at fault, some other prices will be wrong too, on any account.
"""Experiment 4: try other list prices and discounts."""
from decimal import Decimal, ROUND_HALF_UP
CASES = [("1.25", 10), ("1.15", 10), ("1.50", 15), ("2.00", 10), ("4.80", 10)]
print("list disc float+round Decimal half up stored float value")
for price, disc in CASES:
as_float = round(float(price) * (1 - disc / 100), 2)
exact = Decimal(price) * (100 - disc) / 100
correct = exact.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
stored = Decimal(float(price) * (1 - disc / 100))
flag = "" if Decimal(str(as_float)) == correct else " <- WRONG"
print(f"{price:<5} {disc:>3}% {as_float:<11} {correct:<15} {str(stored)[:22]}{flag}")list disc float+round Decimal half up stored float value
1.25 10% 1.12 1.13 1.125 <- WRONG
1.15 10% 1.03 1.04 1.03499999999999992006 <- WRONG
1.50 15% 1.27 1.28 1.27499999999999991118 <- WRONG
2.00 10% 1.8 1.80 1.80000000000000004440
4.80 10% 4.32 4.32 4.32000000000000028421CASESlists a few list prices with discounts. They are strings, so no float error enters before the sum.as_floatis what the service does: float arithmetic, thenround().correctis the same sum inDecimal, rounded half up.storedshows the exact value that the float holds, so you can see whether it sits just below a half.
A second cause appears. For 1.15 with 10% off, the true price is 1.035, an exact half. But the float is stored as 1.03499999 and some more nines, a hair below the half, so round() goes down to 1.03. The same happens for 1.50 with 15% off. Prices such as 2.00 and 4.80 are fine.
This also rules out the stored-discount idea. The pattern follows the price and the discount, not the account. For completeness, you still check the stored value. In the real service that would be a short look in the Django shell. The lines below are an excerpt from such a session, shown without a run.
>>> from customers.models import Customer
>>> Customer.objects.get(account_code="TC7-0042").contract_discount
Decimal('10.00')Excerpt: reading the stored discount in the Django shell. Not run here.
The stored discount is 10%, as finance said.
The hypothesis log: recording what you learned
Here is the log for this defect. A reviewer can read it in one minute and see what you tried, what you found and what is still open.
| # | Hypothesis | Experiment | Result | Status |
|---|---|---|---|---|
| 1 | Accounts system is wrong | Ask finance for the rule; work the sum by hand | Policy is round half up. 1.125 gives 1.13, so the accounts system is right. | Ruled out |
| 2 | VAT rounding | Gap for 1, 10 and 40 packs | Gap is 1p, 10p, 40p. It grows with quantity. | Ruled out |
| 3 | Rounding per order, not per line | Same experiment | A total-level rounding cannot give 40p. The unit price is already rounded to 1.12. | Ruled out |
| 4 | Wrong stored discount | Read the discount; try other prices | Discount is 10%. Wrong results follow the price, not the account. | Ruled out |
| 5 | Float arithmetic with built-in round() | Print values; compare with Decimal; try other prices | Two effects found: an exact half goes to even, and some products are stored just below a half. | Supported, not yet traced to a change |
Do not stop at 'supported'. The last row is still open in one way: you know the cause, but not yet when it arrived. The next lesson uses version history to find the commit that introduced it.
Using an AI assistant to brainstorm hypotheses
An assistant can be a useful brainstorming partner. It has seen many bugs, so it can suggest causes you did not think of and experiments to separate them. But it has not seen your system. Everything it says is a hypothesis for your log, never a result.
- Give it your question, your facts and the experiments you have already run, with their results.
- Ask for hypotheses, each with a prediction and a cheap experiment.
- Ask it to include the possibility that your reference is wrong.
- Add its ideas to the log. Run the experiments yourself. Record real results.
Conclusion and your next step
You now know how to move from a failing case to evidence. You list rival explanations, rank them, run one cheap experiment at a time and keep a log. For the napkin bug, four ideas were ruled out and one survived, with two precise effects: an exact half penny rounded to even, and prices stored just below a half.
Your next step: find out when this behaviour arrived. Open Using History and Bisection and let git find the exact commit for you.
For a prompt that follows the same method, read AI-Assisted Debugging: A Scientific-Method Prompt Framework. The prompt library entry Stack Trace Root-Cause Analysis is a good companion when you have an error message.
Reusable prompt
Hypothesis log builder
Turns your facts and experiment results into a hypothesis log and proposes the next cheapest experiment.
I am debugging a pricing defect. Help me keep a hypothesis log. Do not tell me the cause.
Question: why does contract account TC7-0042 pay 1.12 per pack of NAP-100 instead of 1.13?
Facts: list price 1.25; contract discount 10%; finance policy is round each contract unit price half up to the penny; the service is Python and uses legacy/pricing_v1.py contract_unit_price.
Experiments I have run, with real results:
- Gap for 1, 10 and 40 packs: 1p, 10p, 40p.
- Printed the float product: it is exactly 1.125, and round(1.125, 2) gives 1.12.
Give me a table with these columns: hypothesis, prediction (if true, I will see...), cheapest experiment, status (ruled out, supported, open). Include at least five hypotheses, and include the possibility that the reference (finance policy or the accounts system) is wrong.
Mark which hypotheses my results already rule out and why. Then name the single next experiment that would tell the remaining ideas apart.Show the reusable template
Replace each {{placeholder}} with your own details.
I am debugging a defect. Help me keep a hypothesis log. Do not tell me the cause.
Question: {{question}}
Facts: {{facts}}
Experiments I have run, with real results:
{{experiments_and_results}}
Give me a table with these columns: hypothesis, prediction (if true, I will see...), cheapest experiment, status (ruled out, supported, open). Include at least {{minimum_hypotheses}} hypotheses, and include the possibility that the reference (policy, spec or another system) is wrong.
Mark which hypotheses my results already rule out and why. Then name the single next experiment that would tell the remaining ideas apart.Expected output and limitations
A table with the four columns you asked for, a status for each row that follows from the results you gave, and one proposed next experiment. A good answer uses only your facts and says 'open' where your results do not decide.
| Hypothesis | If true, I will see | Cheapest experiment | Status |
|---|---|---|---|
| Rounding rule differs from policy | An exact half goes down | Compare ROUND_HALF_EVEN and ROUND_HALF_UP in Decimal | Supported by the 1.125 result |
| Float stores prices inexactly | Some other prices round wrongly | Try other prices and print exact stored values | Open |
| Wrong stored discount | Other products on this account are wrong | Read the stored discount | Open |
| Accounts system is wrong | Policy gives 1.12 | Re-read the policy with finance | Open |
| VAT rounding | A gap that does not grow with quantity | Already tested | Ruled out: the gap grows with quantity |
Next experiment: run a few other prices and discounts through the service and compare with Decimal.Limitations to keep in mind
- The sample is illustrative. The assistant has not run anything, so 'ruled out' and 'supported' only repeat your results.
- It may add generic ideas that do not apply to your system. Keep only those you can test.
- It may claim a result it cannot know. Record only results that you saw yourself.
- Its ranking is a suggestion. Rank by your own evidence and the cost of each experiment.
Common errors and how to fix them
Testing only the favourite idea
Why it happens: You are sure of the cause and look only for proof of it.
Fix: List at least three rivals, and choose an experiment that could prove your favourite wrong.
Changing several things between runs
Why it happens: You edit the code, the data and the settings together to save time.
Fix: Change one thing, run, record the result, then continue.
Not recording ruled-out ideas
Why it happens: Dead ends feel like wasted time, so nobody writes them down.
Fix: Log every idea with its result. The next person, or you in a week, will not repeat the work.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
Build a hypothesis log for your defect
Using the reproduction from the previous lesson, write at least five hypotheses for your defect, rank them, run an experiment for each and record the results.
You will need
- Your reproduction card from the previous lesson.
- The code you are allowed to run, and a way to print or log values.
- The table layout from this lesson.
Acceptance criteria
Your work is done when every one of these is true.
Hints (3)
- If you are short of ideas, ask an assistant for more. Then test them rather than trust them.
- Cheap checks first: reread the report, check the version, print one value.
- If two ideas always fit your result, look for an input where they predict different answers.
Show a model answer
A good log reads like a short story: question, five or more ideas, an order of testing with reasons, and a result beside each. It contains at least one ruled-out idea and one idea the author expected to be true but was not. It says what is still open. A weak log lists only the final cause, has no predictions and records no experiment that could have gone the other way.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. Ranking balances likelihood and cost. A five-minute check can narrow the list a lot. Cheap ideas are not more often right, and expensive tests are sometimes necessary, only later.
Show the answer and explanation
Answer: B. Rounding a total moves it by half a penny at most, so a 40p gap must come from something repeated for each pack. The first option is the tempting wrong answer, because rounding is the topic, but it fails the prediction.
Show the answer and explanation
Answer: B. The idea might be right, so ignoring it is wrong. Fixing code on the strength of a claim you have not tested is also wrong. A hypothesis in the log gets a prediction and an experiment, like any other.
Frequently asked questions
What is the difference between a hypothesis and a guess?
A hypothesis comes with a prediction you can check, such as 'if this is the cause, the gap will grow with quantity'. A plain guess has nothing to test. Writing the prediction turns a guess into something you can prove wrong.
How many hypotheses should I write?
Aim for at least five, including one that says your reference is wrong. More ideas stop you from falling in love with the first one. You can remove duplicates later.
What if every experiment is inconclusive?
Look for a smaller, sharper experiment, or an input where two ideas predict different results. Also check that your reproduction is still failing for the reason you think. If you are stuck, use history, which is the next lesson.
Do I need a log if I find the cause quickly?
A short log still helps. It shows reviewers what you ruled out, and it protects you when the first fix turns out to be incomplete. For a five-minute bug, three lines are enough.
- Written by
- PromptFable Editorial
- Last updated 19 Nov 2026
- Review
- Reviewed by Waseem Nadir, Technical Reviewer
- Last reviewed 27 Nov 2026
References
Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.
- 15. Floating-Point Arithmetic: Issues and Limitations(opens in a new tab)
Python Software Foundation · Official documentation · Why some decimal numbers are stored slightly off in binary floats.
- decimal — Decimal fixed-point and floating-point arithmetic(opens in a new tab)
Python Software Foundation · Official documentation · Includes the rounding modes ROUND_HALF_UP and ROUND_HALF_EVEN.
- pdb — The Python Debugger(opens in a new tab)
Python Software Foundation · Official documentation
- logging — Logging facility for Python(opens in a new tab)
Python Software Foundation · Official documentation
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.