In this lesson, you will learn how to calculate the sum and average of the first n natural numbers in Python.
Also, you will get to know how to calculate the addition and average of user-entered numbers, list of numbers. And the use of built-in function sum()
.
This tutorials is part of Python Basics.
Table of contents
Sum and average of first n natural numbers
Sum and average of n
numbers in Python
- Accept the number n from a user
Use input() function to accept integer number from a user.
- Run a loop till the entered number
Next, run a for loop till the entered number using the
range()
function. In each iteration, we will get the next number till the loop reaches the last number, i.e.,n
. - Calculate the sum
In each iteration, keep adding the current number into the sum variable to calculate the addition. Use a formula
sum = sum + current number
. - Calculate the average
At last, after the loop ends, calculate the average using a formula
average = sum / n
. Here, Then
is a number entered by the user.
Program:
Output Enter number 10 Sum of first 10 numbers is: 55 Average of 10 numbers is: 5.5
Use built-in function sum()
You can also take the advantage of built-in function sum()
to calculate the sum of an iterable like range and list.
Sum and average of a list
Use the below steps to calculate the sum and average of numbers present in the given list.
- Iterate a Python list using a
for
loop and add each number to a sum variable. - To calculate the average, divide the sum by the length of a given list (total numbers in a list)
Sum and average using a mathematical formula
In the above programs, we calculated the sum and average using the looping technique. Now, let’s see how to calculate the sum and average directly using a mathematical formula.
Assume n
is a number
- The sum of the first n natural number =
n * (n+1) / 2
- the average of first n natural number =
(n * (n+1) / 2) / n
Example
Sum and average of multiple user-entered numbers
If you want to calculate the sum and percentage of multiple user-entered numbers, please refer to the following program.
Refer to how to accept list of numbers as a input in Python.
Output
Enter numbers separated by space 10 20 30 40 50 Sum = 150 Average = 30.0
While loop to calculate sum and average
You can also use the Python while loop to calculate the sum and average of n numbers. Follow these steps:
- Decide the value of
n
. - Run a
while
loop till n is greater than zero. - In each iteration, add the current value of
n
to the sum variable and decrementn
by 1. - Calculates the average by dividing the sum by
n
(total numbers).
Practice Problem: Add two matrices in Python
Solution
Next steps
Let me know your comments and feedback in the section below.
Solve: