Project: Average of five numbers
Write a program that reads five numbers from the keyboard and prints their average. It should accept negative numbers and decimals. When you run it, the output should match this format:
Please enter five numbers.
-5.4
2.1
7.0
134.8
-20.0
The calculated average of those numbers is:
23.7
Save the file as calculate_average.py.
Show a solution
Try the project on your own first. This is one working solution. Press Run, and a box asks for each input. Type the sample values from the project description to see the same output.
About the tests below. The tests in the next box will look confusing, and maybe intimidating. That is normal. They use ideas you have not learned yet, such as functions and classes, so most of the code will not make sense yet. You do not need to understand how they work. Read the test names, which each describe one rule the program must follow, and the expected values. Tests get easier to read as you learn more, and by the end of the course you will read them comfortably. Come back to them after each section.
Here is what the words mean, in case you are curious:
- A test calls your code with chosen inputs and checks the result. If the result is wrong, the test fails and names the line.
- Coverage measures which lines of your code the tests actually ran. A line
no test reaches is a line nobody has checked. The solutions here are tested to
100% of their lines and branches, meaning every
ifwas tested both ways. - Coverage is not enough. A test can run a line without checking its result.
To check the tests themselves, we use mutation testing: a tool makes small
deliberate bugs in the solution, such as changing
<to<=or+to-, and every one of them must make at least one test fail. Try it yourself: in the tests box below, change/ 5to/ 4in the copy of the program kept inPROGRAM, press Run, and watch a test catch it. - Equivalent changes. Sometimes a small change does not alter what the
program does. For example, if a loop only runs while
guess != secret, thenguess < secretandguess <= secretbehave the same. No test can tell them apart, so those lines carry the comment# pragma: no mutateand a note saying why.
To measure coverage on your own project in the VS Code terminal, install the
tool once, then run your tests under it and print the report. The report lists
any line your tests missed. (On Windows, use python in place of python3.)
python3 -m pip install coverage
python3 -m coverage run --branch -m unittest
python3 -m coverage report -m
These tests check the solution above. They run a copy of the program, kept in PROGRAM, and give it pretend input. The testing tools here are not part of the course yet, so do not worry about how they work. Read the test names and the expected outputs: together they list what the program must do. Press Run to run the tests.