Python Program to Calculate Sum and Average of N Numbers
This guide explains how to write a Python program to calculate the sum and average of N numbers. We'll cover the basic approach, provide a complete Python program, explain the formula, and include a worked example.
How to Calculate Sum and Average
Calculating the sum and average of a set of numbers is a fundamental mathematical operation. The sum is simply the total of all numbers added together, while the average (or mean) is the sum divided by the count of numbers.
Key Formulas
Sum (S) = n₁ + n₂ + n₃ + ... + nₙ
Average (A) = Sum / N
Where N is the count of numbers.
Steps to Calculate
- Count the total number of values (N).
- Add all the numbers together to get the sum.
- Divide the sum by the count of numbers to get the average.
This process can be automated in Python using loops and basic arithmetic operations.
Python Program Example
Here's a complete Python program that calculates the sum and average of N numbers entered by the user:
Note: This program assumes the user will enter valid numbers. For production use, you should add input validation.
# Python program to calculate sum and average of N numbers
# Get the count of numbers
n = int(input("Enter the count of numbers: "))
# Initialize sum
total = 0
# Get numbers and calculate sum
for i in range(n):
num = float(input(f"Enter number {i+1}: "))
total += num
# Calculate average
average = total / n
# Display results
print(f"\nSum of the numbers: {total}")
print(f"Average of the numbers: {average:.2f}")
How the Program Works
- The program first asks for the count of numbers (N).
- It then uses a loop to collect each number and adds it to the total sum.
- After collecting all numbers, it calculates the average by dividing the sum by N.
- Finally, it displays both the sum and average.
Formula Used
The calculation follows these mathematical principles:
Sum Calculation
S = Σ (from i=1 to N) nᵢ
Where S is the sum, N is the count of numbers, and nᵢ represents each individual number.
Average Calculation
A = S / N
Where A is the average, S is the sum, and N is the count of numbers.
These formulas are implemented directly in the Python program using basic arithmetic operations and loops.
Worked Example
Let's walk through an example with 5 numbers: 10, 20, 30, 40, and 50.
| Step | Calculation | Result |
|---|---|---|
| 1 | Count of numbers (N) | 5 |
| 2 | Sum (S) = 10 + 20 + 30 + 40 + 50 | 150 |
| 3 | Average (A) = 150 / 5 | 30.00 |
In this example, the sum is 150 and the average is 30.00.