Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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
14

To 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. 1

    Print the average time of the week with statistics.mean(), rounded to one decimal place: Average: 118.6. Keep the line with minutes as it is: the exercise also tries your program with other weeks.

  2. 2

    Below, print the median with statistics.median(): Median: 100. One long Saturday pulled the average up, but the median shows a typical day.

Back

7/8

  1. 1. Importing a Module
  2. 2. Rounding
  3. 3. Quiz: Rounding
  4. 4. Importing with from
  5. 5. Quiz: Imports
  6. 6. Random Numbers
  7. 7. Average and Median
  8. 8. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.