Average and Median
The module statistics works with lists of numbers. Its function mean() gives their average (mean is the word mathematicians use), and median() their median, the value in the middle:
import statistics
scores = [12, 15, 14, 13, 95]
print(statistics.mean(scores))
print(statistics.median(scores))29.8
14To find the median, put the numbers in order and take the one in the middle: 12, 13, 14, 15, 95. When there's an even number of them, two are in the middle, and the median is their average: the median of [1, 2, 3, 4] is 2.5.
Why two kinds of middle? Four of the five scores are between 12 and 15, but one player scored 95, and that one score pulls the average up to 29.8, more than any of the other four got. The median, 14, isn't moved by one extreme value, so it tells you better what a typical score is.
You could write both yourself: the average is sum(scores) / len(scores), as in the lesson on loops, and the median is the middle element of sorted(scores), with an extra step for an even count. But someone has already written them, tested them and put them in a module. That's what modules are for: you don't have to write everything yourself.
An empty list has no average: statistics.mean([]) ends with statistics.StatisticsError: mean requires at least one data point. The part before the dot says that this kind of exception comes from the module statistics. Modules can have exceptions of their own, and you catch them with try and except as you learned in Errors and Exceptions, with the module's name in front: except statistics.StatisticsError:.
Instructions
- 1
Print the average time of the week with
statistics.mean(), rounded to one decimal place:Average: 118.6. Keep the line withminutesas it is: the exercise also tries your program with other weeks. - 2
Below, print the median with
statistics.median():Median: 100. One long Saturday pulled the average up, but the median shows a typical day.