How to Calculate Average of Numbers in Python

The average or arithmetic mean of a collection of numbers is calculated by adding the numbers and then dividing it with the number of numbers in the collection. The arithmetic mean is used in almost all scientific disciplines for analysis.

Consider the collection of numbers – 5,7,8,12. The arithmetic mean is (5+7+8+12)/4 = 8.

There are multiple approaches to finding average of numbers in python. Here are some examples,

1. Find average of numbers using for loop in python,

numbers_str = input("Enter numbers separated by spaces: ")
numbers = [float(num) for num in numbers_str.split()]

total = 0;
for x in numbers:
    total = total + x
print("Average of ", numbers, " is ", total / len(numbers))

2. Find average of numbers using built-in functions in python,

numbers_str = input("Enter numbers separated by spaces: ")
numbers = [float(num) for num in numbers_str.split()]

print("Average of ", numbers, " is ", sum(numbers) / len(numbers))

3. Find average of numbers using module functions in python,

import statistics
numbers_str = input("Enter numbers separated by spaces: ")
numbers = [float(num) for num in numbers_str.split()]

print("Average of ", numbers, " is ", statistics.mean(numbers))

Here is the output of the above programs in console,

python3 avg3.py
Enter numbers separated by spaces: 5 7 8 12
Average of  [5.0, 7.0, 8.0, 12.0]  is  8.0

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution! Please email us.

Leave a Reply