Course 5.2Lesson 5 of 6
A function is only useful if it is right, so test it. A test is a table of cases: an input, and the answer that you expect from the rules, not from the function. Include the edges, such as 49, 50 and 51 for a grade, the smallest and the biggest allowed input, and a case with an unusual value. A loop over the table prints PASS or FAIL for each case. A short note in triple quotes, the docstring, says what the function does and can be read back with help. When a test fails, follow the function by hand for that input.
Try the code and the simulations beside the lesson.
After this lesson you can
You write a function once, and then you trust it in many places. A fault in a function is a fault everywhere. So a function deserves a test. A test is a set of calls with answers that you know before you run them.
You did this in the chapter on decisions with a table of marks. A function makes it neater: the test calls the function, and the function does the work.
To see the test work, break the function: change mark >= 75 to mark > 75 and run again. The line for 75 now says FAIL 75 expected B got C. The test found the fault in one second, and it also shows exactly which input went wrong.
You cannot test every number. Choose well.
> and >= live here.Eight to twelve cases usually find most faults.
The expected answers come from the rule, not from the function. That is why a wrong function cannot pass them.
A function should say what it does. The usual way is a short note in triple quotes as the first line of the body. It is called a docstring.
A good docstring says what the function gives, in one sentence, and mentions any surprising input. You do not explain how: the code shows that.
Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
PASS or FAIL runs all the cases.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.