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, Thenis 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
forloop 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
whileloop till n is greater than zero. - In each iteration, add the current value of
nto the sum variable and decrementnby 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:

Hello Vishal,
Please can you help me with this question below.
Given the final percentage a student has gotten at the end of a semester, you need to write a program that decides if the student has passed or failed the semester.
If the percentage is higher than or equal to 60, the student has passed the semester. If the percentage is lower than 60, the student has failed the semester.
However, the percentage is not the only thing that determines if a student has passed or failed. A student does not pass if their score is 5 points below the class average.
For instance, if the average class score is 70, the student must have a minimum score of 65 to pass.
If the average class score is 50, the student still needs a score of 60 to pass based on our first condition.
Hi, can you help me with this code as I am not getting the right total sum and confused about where have I gone wrong?
sum = 0SMALL_MAH = 3000
MEDIUM_MAH = 10000
LARGE_MAH = 20000
# Paste the `recommend_power_bank` function from your Part A solution here
def recommend_power_bank(x):
if x <= SMALL_MAH:
return str('small')
elif x < MEDIUM_MAH:
return str('large')
# Write the rest of your solution here
battery = int(input('Device battery capacity (mAH): '))
more = input('More? (y/n): ')
battery = 0
capacity = battery + battery
while more == 'y':
battery = int(input('Device battery capacity (mAH): '))
capacity = battery + battery
more = input('More? (y/n): ').lower()
if more == 'n':
break
elif more == 'y':
continue
print('Total required battery capacity: ' + str(capacity)+ ' mAH')
print('Power bank recommendation: ' +str(recommend_power_bank(int(capacity))))
Such a profound Python website with excellent information and hands on coding exercises. Very happy and glad I came across your website today. Thank you !
I am glad it helped you, Ramya.
Hi, thank you for the tutorial.
Could you please list then prons and cons of the summation using loop compare to using the math formula directly, regarding the computation space and time complexity.
Many thanks in advance!
Can you help with this please
write a python program that helps users calculate how much they should pay for the items they have put in their cart at the supermarket. Your program should ask the person how many items they put in their cart. Your program should then ask the user to input the price of each item independently.Your program should finally print the total price of all total items
Hey! As it’s my very first program and I tried to solve your question, hope it will help you
Pls also give the right spaces. As it’s mobile typing.
Thank you a lot for all what you do for us (beginner developers).
Best regards
Hey mocine, Thank you. I appreciate your taking the time to express that.
please give me these answer formula. I need this question formula very badly.
Q:1 write a function sum that calculates the sum of begin number to end number by step.
for example:
sum(10,30,3)=> 10+13+16+19+22+25+28Q:2 read a file(input_text.txt)
a. write a program that counts each alphabetic character occurrence. “Yesterday all my troubles seemed so far away.”
b. write a program that sorts in descending order by frequency of character and write the sorted result to a file(sorted_result.txt)
Q.3 write a mini calculator function that has three parameters(first two are operands and the third parameter is the operator) and returns the result.
for example
Q.4 A prime number is a number that has only 1 and itself as a divisor (for example, 1,3,5,7,11,13….)
a. write a function that parameter n is whether a prime number or not.
b. write a program that prints prime numbers between 1 to 100
Thank you advance for your replay.
● Create a new file called while.py
● Write a program that always asks the user to enter a number.
● When the user enters -1, the program should stop requesting the user to
enter a number,
● The program must then calculate the average of the numbers entered
excluding the -1.
● Make use of the while loop repetition structure to implement the
program.
● Compile, save and run your file
can you please help me with this exercise
Hey Thabiso, Please try this
sum=0 count=0; while True: n = input("Enter Number ") n = int (n) if n==-1: break else: count += 1 sum += n print ("sum using while loop ", sum) average = sum / count print("Average using a while loop ", average)using a function calculate and display the average of numbers from 1 to the number entered by the user.
I keep getting errors. Please help!
Hey Ashton, Please let me know the error.
Write a Python program to calculate the average of a given list.
Example : list=[22,25,26,32,41,35,13,16,21]average = 20, len =3
list=[22,25,26,32,41,35,13,16,21]
# program run slowly
# Do you have a better way? Thanks
Python code
Need help in writing code in finding average using while loop.
Can you help with the code
Question
Write a program that first prompts the user to enter the number of numbers to be entered and then uses a while loop to repeatedly prompt the user for those numbers and adds the numbers to a running total. When the correct number of numbers have been entered, the program should print the average.
You can assume the number of numbers entered is an integer greater than zero and that each subsequent number is a float.
While calculating average using while loop why it’s necessary to divide the “sum” by “total_numbers” instead of “n” even if we take n >=1.
Please explain.
Hey Ved Prakash,
we decrementing the value of n in each iteration i.e. n-=1. so and the end of the last iteration of while loop n will become ZERO.
that’s why before the start of the loop iteration we are taking the value of n into another variable which is nothing but total_number.
Hi Vishal,
I have a question when we calculated sum and want to define as str, how to do it. After enter all the marksList and print ( “” +str(sumOfMarks)) and print(“” + str(averageOfMarks)).
I always get the error int and str
#calculate the sum and average
#sumOfMarks = sum(marksList)
#averageOfMarks = sum(marksList)/5