Check Function Results
Compare mean() with independently reasoned answers, use assert for ordinary and boundary cases, and repair one defect exposed by a failing test.
Moving working code into a function should not change its answer. A small test compares the result with an answer reasoned out independently.
Begin with a Known Answer
For [18, 22], the total is 40, the count is 2, and the mean is 20. We can
record that expectation with assert:
assert mean([18, 22]) == 20
Python first calls mean, then compares the actual result with 20. If the
comparison is true, execution continues without output. If it is false,
Python raises an AssertionError.
The expected value must not come from blindly copying the function’s own calculation. Work out a small case by hand so the test supplies independent evidence.
Q1. Choose an independent expectation
What is the best expected result for mean([10, 14])?
Compute it first, then check your number.
HintCalculate without the function
The total is 24 and there are two readings.
SolutionThe expected result is 12
(10 + 14) / 2 is 12, so assert mean([10, 14]) == 12 records an
independently known answer.
Check Ordinary and Boundary Cases
One passing example does not cover every important behavior. We defined four
distinct results for mean:
The first checks ordinary calculation. The second checks one available value.
The last two check that no available readings produce None, whether the list
is empty or contains only unavailable entries.
These tests are evidence, not proof that every possible call is correct. A small set is useful when each case represents a different behavior or boundary.
Q2. Test the unavailable boundary
Which assertion checks the result we defined when every reading is unavailable?
Select one choice, then check.
HintKeep the function contract stable
The earlier function lesson defined None as the result when no numerical
mean is available.
SolutionCheck identity with None
assert mean([None, None]) is None tests the documented no-data behavior.
Let a Failing Test Expose a Defect
This version divides by the length of the list, even though it skips unavailable readings:
The ordinary test may pass when every reading is available. This boundary test fails:
assert mean([18, None, 22]) == 20, "mean should count available readings only"
The message states the expected behavior. Repair the return expression as
total / count; do not weaken the test to match the defect.
Q3. Repair a function from a failing test
Repair the final expression so all four checks pass.
Editable Python
Ready to run.
HintUse the state the loop maintained
The loop already counts only available readings.
SolutionDivide by count
return total / count
A useful test begins with an independently reasoned expectation and covers behavior that could fail differently. The final lesson will make this tested behavior readable at the function boundary.