Find the mean of the numbers in a list in three ways
Expt. No.19
Page No.38
Mean of a list three ways
Aim
To write a Python program that finds the mean of numbers in a list using a loop, using sum() and len(), and using statistics.mean().
Concepts used
Algorithm
- Input the numbers into a list.
- Way 1: add the numbers with a loop and divide by the count.
- Way 2: divide
sum(list)bylen(list). - Way 3: use
statistics.mean(list). - Display all three means.
Program
# Mean of numbers in a list, found three ways import statistics marks = []n = int(input("How many numbers? "))for i in range(n): marks.append(int(input("Enter a number: "))) total = 0for m in marks: total = total + mprint("Mean using a loop :", total / n)print("Mean using sum() / len():", sum(marks) / len(marks))print("Mean using statistics :", statistics.mean(marks))
A marked line continues the line above it. In your file, write it on the same line.
Output
$ python mean_of_list.py
How many numbers? 5
Enter a number: 72
Enter a number: 85
Enter a number: 64
Enter a number: 90
Enter a number: 58
Mean using a loop : 73.8
Mean using sum() / len(): 73.8
Mean using statistics : 73.8
✓ Printed by running this program, not typed by hand.
Result
All three methods gave the same mean, 73.8, for the marks 72, 85, 64, 90 and 58 (total 369 ÷ 5).
Viva voce: what the examiner may ask
01What is the mean?
The sum of the values divided by how many values there are.
02How do you use a function from the statistics module?
Import the module with import statistics, then call statistics.mean(...).
03What does / return for 369 / 5?
73.8, a float. / always returns a float in Python 3.
Variations for the lab test
- Also find the median and mode with the statistics module.
- Display the numbers that are above the mean.
- Find the mean of numbers stored in a tuple.
! Common mistake Writing
total / 0 happens if n is 0; the program then stops with ZeroDivisionError.