Functions you can test
Why it matters Training code can be wrong and still run. A small test that catches a wrong answer is the cheapest insurance you will ever buy.
A test is a few lines that call your function on a case where you already know the answer, and complain loudly if it is wrong. Python's assert does exactly that: assert mean([2, 4]) == 3 does nothing if true and stops with an error if false.
Tiny numbers
The mean of [2, 4] is 3. The mean of [5] is 5. The mean of [1, 2, 3, 4] is 2.5. A good test picks cases that catch different mistakes: an even split, a single item, and a result that is not a whole number.
Test: code that checks other code against answers you worked out by hand.
Here you write a checker that takes any mean function and tests it. We will hand it a correct mean and some broken ones. A good checker passes the correct one and catches the broken ones.
Recap Choose cases where you know the answer and where likely mistakes would show.
Words and symbols in this lesson
- mean, spread
- the average, and roughly how far values sit from it (standard deviation)
Write mean(xs), then write check_mean(fn), which calls fn on at least three cases and uses assert to check each answer.
The hidden test runs your check_mean on a correct mean (it must not complain) and on three broken means: one that rounds down to a whole number, one that divides by the wrong count, and one that only looks at the first two items. Your checker must catch all three.
Spotted a problem in this lesson? Report it · Ask about this lesson
This exercise opens soon
Finish the lesson before it and this one unlocks. The whole course is free, no account needed, and you can read this lesson right now.
This browser is blocking cookies for learn.floati.life, so lessons you finished here cannot open in order. Allow cookies for this site and reload.