Python Program to Calculate Average of N Numbers
Calculating the average of N numbers is a fundamental statistical operation. This guide explains how to write a Python program to calculate the average of any set of numbers, including step-by-step code examples and a working calculator.
How to Calculate the Average
The average (also known as the arithmetic mean) of a set of numbers is calculated by summing all the numbers and then dividing by the count of numbers. The formula is:
Average = (Sum of all numbers) / (Count of numbers)
For example, if you have the numbers 4, 7, 12, and 15:
- Sum the numbers: 4 + 7 + 12 + 15 = 38
- Count the numbers: There are 4 numbers
- Calculate the average: 38 / 4 = 9.5
The average of these numbers is 9.5. This method works for any set of numbers, regardless of how many there are.
Python Program to Calculate Average
Here's a complete Python program that calculates the average of N numbers:
This program uses Python's built-in functions to handle the calculation. It first asks the user to input the numbers, then calculates and displays the average.
# Python program to calculate average of N numbers
def calculate_average():
# Get input from user
numbers = input("Enter numbers separated by spaces: ")
# Convert input string to list of floats
num_list = [float(num) for num in numbers.split()]
# Calculate average
average = sum(num_list) / len(num_list)
# Display result
print(f"The average of the numbers is: {average:.2f}")
# Run the program
calculate_average()
How the Program Works
- The program prompts the user to enter numbers separated by spaces.
- It converts the input string into a list of floating-point numbers.
- It calculates the average using the formula: sum of numbers divided by count of numbers.
- The result is displayed with 2 decimal places for readability.
You can modify this program to accept input from a file or other data source as needed.
Example Calculation
Let's walk through an example calculation using the numbers 10, 20, 30, and 40.
When you run the program and enter "10 20 30 40", the output will be: "The average of the numbers is: 25.00"
Here's how the calculation works:
- Sum: 10 + 20 + 30 + 40 = 100
- Count: 4 numbers
- Average: 100 / 4 = 25.00
This shows that the average of these four numbers is 25.00.