Editor

Python Program to Find the Average of Numbers

Beginner · Basics

The average, or mean, of a set of numbers is their total divided by how many numbers there are: the average of 4, 8 and 15 is (4 + 8 + 15) / 3 = 9. This program finds the average of a list of marks.

Program

average_of_numbers.py
marks = [78, 92, 65, 88, 71] # or: marks = [float(x) for x in input("Enter numbers: ").split()]
total = 0
for m in marks:
total += m
count = len(marks)
if count == 0:
print("No numbers to average")
else:
average = total / count
print("Numbers:", marks)
print("Total:", total)
print("Count:", count)
print(f"Average: {average:.2f}")
Output
Numbers: [78, 92, 65, 88, 71]
Total: 394
Count: 5
Average: 78.80

How it works

  1. The loop adds every mark to total.
  2. len(marks) gives the count, which is how many numbers there are.
  3. The average is the total divided by the count, and an empty list is caught first because dividing by zero is an error.
  4. :.2f prints the average with two decimal places.

Other ways to write it

Using sum() and len()

Using sum() and len()
marks = [78, 92, 65, 88, 71]
average = sum(marks) / len(marks)
print(f"Average of {marks} = {average:.2f}")
Output
Average of [78, 92, 65, 88, 71] = 78.80

The built-ins sum() and len() replace the loop and the counter.

Mean, median and mode

Mean, median and mode
import statistics
marks = [78, 92, 65, 88, 71, 92]
print("Mean:", round(statistics.mean(marks), 2))
print("Median:", statistics.median(marks))
print("Mode:", statistics.mode(marks))
Output
Mean: 81
Median: 83.0
Mode: 92

The statistics module also gives the median, the middle value, and the mode, the most common value.

Try it yourself

Make the program also print the highest mark, the lowest mark and how many marks are above the average.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises