Python Program to Calculate Sum of N Numbers
This guide explains how to write a Python program to calculate the sum of N numbers. We'll cover the basic approach, provide a working code example, and include a calculator to test your understanding.
How to Calculate Sum of N Numbers
Calculating the sum of N numbers is a fundamental programming task. The process involves:
- Collecting the numbers you want to sum
- Initializing a sum variable to zero
- Iterating through each number and adding it to the sum
- Returning or displaying the final sum
This method works for any number of inputs, whether you know the count in advance or need to process an unknown quantity of numbers.
Python Program to Calculate Sum
Here's a complete Python program that calculates the sum of N numbers:
# Python program to calculate sum of N numbers
def calculate_sum():
# Get the number of elements
n = int(input("Enter the number of elements: "))
# Initialize sum
total = 0
# Get numbers and add to total
for i in range(n):
num = float(input(f"Enter number {i+1}: "))
total += num
# Display the result
print(f"The sum of {n} numbers is: {total}")
# Call the function
calculate_sum()
This program:
- Prompts the user for the count of numbers
- Uses a loop to collect each number
- Accumulates the sum in a variable
- Prints the final result
Worked Example
Let's walk through an example where we sum 3 numbers: 5, 10, and 15.
- User enters 3 as the count of numbers
- Program prompts for and receives 5, 10, and 15
- Sum calculation: 0 + 5 = 5; 5 + 10 = 15; 15 + 15 = 30
- Final output: "The sum of 3 numbers is: 30.0"
Note: The program handles both integers and floating-point numbers, making it versatile for different types of calculations.
Formula Used
The sum of N numbers can be calculated using the following formula:
Sum = num₁ + num₂ + num₃ + ... + numₙ
Where:
- num₁, num₂, ..., numₙ are the individual numbers
- N is the count of numbers
In the Python program, this is implemented through iteration and accumulation in a loop.