PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python » Python program to calculate sum and average of first n natural numbers

Python program to calculate sum and average of first n natural numbers

Updated on: June 16, 2021 | 26 Comments

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
    • Use built-in function sum()
  • Sum and average of a list
  • Sum and average using a mathematical formula
  • Sum and average of multiple user-entered numbers
  • While loop to calculate sum and average
  • Practice Problem: Add two matrices in Python
    • Solution
  • Next steps

Sum and average of first n natural numbers

Sum and average of n numbers in Python

  1. Accept the number n from a user

    Use input() function to accept integer number from a user.

  2. 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.

  3. 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.

  4. Calculate the average

    At last, after the loop ends, calculate the average using a formula average = sum / n. Here, The n is a number entered by the user.

Program:

n = int(input("Enter number"))
sum = 0
# loop from 1 to n
for num in range(1, n + 1, 1):
    sum = sum + num
print("Sum of first ", n, "numbers is: ", sum)
average = sum / n
print("Average of ", n, "numbers is: ", average)Code language: Python (python)
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.

n = 10
res = sum(range(1, n + 1))
print("Sum of first ", n, "numbers is: ", res)

# Output Sum of first  10 numbers is:  55Code language: Python (python)

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)
# list with int and floats
num_list = [10, 20.5, 30, 45.5, 50]

# Approach 1 using built-in function sum
res = sum(num_list)
avg = res / len(num_list)
print("sum is: ", res, "Average is: ", avg)
# Output sum is:  156.0 Average is:  31.2

# Approach 2 using a for loop
res1 = 0
for num in num_list:
    res1 += num
avg1 = res1 / len(num_list)
print("sum is: ", res1, "Average is: ", avg1)
# Output sum is:  156.0 Average is:  31.2Code language: Python (python)

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

n = 20
# formula to calculate sum
res = n * (n + 1) / 2
print('sum of first', n, 'numbers is:', res)
# Output sum of first 20 numbers is: 210.0

# formula to calculate average
average = (n * (n + 1) / 2) / n
print('Average of first', n, 'numbers is:', average)
# Output Average of 20 numbers is: 10.5
Code language: Python (python)

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.

input_string = input('Enter numbers separated by space ')
print("\n")
# Take input numbers into list
numbers = input_string.split()

# convert each item to int type
for i in range(len(numbers)):
    # convert each item to int type
    numbers[i] = int(numbers[i])

# Calculating the sum and average
print("Sum = ", sum(numbers))
print("Average = ", sum(numbers) / len(numbers))
Code language: Python (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 decrement n by 1.
  • Calculates the average by dividing the sum by n (total numbers).
n = 20
total_numbers = n
sum = 0
while n >= 0:
    sum += n
    n -= 1
print("sum =", sum)
# Output sum = 210

average = sum / total_numbers
print("Average = ", average)
# Output Average =  10.5
Code language: Python (python)

Practice Problem: Add two matrices in Python

matrixOne = [[6,9,11],
    [2 ,3,8]]

matrixTwo = [[15,18,11],
    [26,16,19]]

# Result shoud be
result = [[0,0,0],
         [0,0,0]]Code language: Python (python)

Solution

matrixOne = [[6,9,11],
    [2 ,3,8]]

matrixTwo = [[15,18,11],
    [26,16,19]]

result = [[0,0,0],
         [0,0,0]]

# First iterate rows
for i in range(len(matrixOne)):
   # Second iterate columns
   for j in range(len(matrixOne[0])):
       result[i][j] = matrixOne[i][j] + matrixTwo[i][j]
print("Addition of two Matrix In Python")
for res in result:
   print(res)Code language: Python (python)

Next steps

Let me know your comments and feedback in the section below.

Solve:

  • Python exercise for beginners
  • Python Quiz for beginners

Filed Under: Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Comments

  1. Princewill says

    November 4, 2021 at 4:10 pm

    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.

    Reply
    • Damascene says

      July 8, 2022 at 10:30 pm

      # Calculation of pass marks
      
      passMarks=60
      
      classAverage=float(input('Please enter your class average marks: '))
      studentMarks=float(input('please enter your score: '))
      
      if (studentMarks>=(classAverage-5))and (studentMarks>=passMarks):
          print('Congz you have passed the semester')
      
      
      else:
          print('unfortunately you failed the semester')
      Reply
  2. Bill says

    April 17, 2021 at 8:30 am

    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?

    
    SMALL_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))))
    Reply
    • Damascene says

      July 8, 2022 at 11:00 pm

      SMALL_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('medium')
           else:
                return str('large')
      # Write the rest of your solution here
      
      
      while True:
               batteryCapacity = int(input('Device battery capacity (mAH): '))  
               newCapacity=recommend_power_bank(batteryCapacity)
               print('Total required battery capacity:',batteryCapacity,' mAH')
               print('Power bank recommendation: ',newCapacity)
               
               more = input("press 'q' to quit or enter to continue: ")   
               if more == 'q':
                  break
      
      print('Ok Bye!')
      Reply
    • Usman Zafar says

      December 5, 2022 at 10:46 am

      sum = 0

      SMALL_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))))

      Reply
  3. Ramya says

    January 31, 2021 at 1:06 am

    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 !

    Reply
    • Vishal says

      January 31, 2021 at 10:11 am

      I am glad it helped you, Ramya.

      Reply
  4. Shadi says

    September 13, 2020 at 9:02 pm

    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!

    Reply
  5. Anna says

    July 14, 2020 at 5:03 pm

    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

    Reply
    • Chikki says

      August 27, 2020 at 7:26 pm

      Hey! As it’s my very first program and I tried to solve your question, hope it will help you

      n = int(input("Enter the total item no. In cart "))
      pay=0
      I=1
      while (i <= n):
          Print("Enter the price of item no. ",i )
          item = float(input())
          pay = pay+item
          i = i+1
      print("your total payable amount is: ")
      Reply
      • Chikki says

        August 27, 2020 at 7:28 pm

        Pls also give the right spaces. As it’s mobile typing.

        Reply
      • Damascene says

        July 9, 2022 at 6:41 pm

        #Cost of item
        
        #Ask the user to enter the number of items that he wants to put in the cart.
        
        nItems=input('Please enter the number of items that you want to put in the cart:')
        nItems=int(nItems)
        cost=0
        i=1
        while (i<=nItems):
        
            
        #Ask the user to enter the cost of each item.
            costItem=int(input('please enter the cost of one item: '))
        
            cost=cost+costItem
            i=i+1
        
        print(' the cost of item is',cost)
        Reply
  6. mocine says

    March 26, 2020 at 7:22 pm

    Thank you a lot for all what you do for us (beginner developers).
    Best regards

    Reply
    • Vishal says

      March 26, 2020 at 8:55 pm

      Hey mocine, Thank you. I appreciate your taking the time to express that.

      Reply
  7. Daniel says

    December 13, 2019 at 1:17 pm

    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+28
    Q: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.”

    'a': 5
    'b': 1
    'c': 0
    'd': 2
    'e': 6
    

    b. write a program that sorts in descending order by frequency of character and write the sorted result to a file(sorted_result.txt)

    'e': 6
    'a': 5
    'd': 2
    'b': 1
    

    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

    calculator(35,5, '+' : 35+5=>40
    calculator(10, 15, '-'): 10-15=> -5
    

    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.

    Reply
    • Damascene says

      July 9, 2022 at 6:54 pm

      #Ask the user to enter the starting number.
      startingNumber=int(input('please enter the starting number: '))
      
      #Ask the user to enter the ending number.
      endingNumber=int(input('Enter the ending number: '))
      #Ask the user to enter interval between two numbers
      interval=int(input('Enter interval between two numbers: '))
      sum=0
      
      for i in range(startingNumber,endingNumber,interval):
          sum=sum+i
      
      print('The sum is:',sum)
      Reply
  8. Thabiso says

    October 30, 2019 at 6:18 pm

    ● 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

    Reply
    • Vishal says

      October 31, 2019 at 9:24 am

      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)
      
      Reply
      • Ashton says

        July 6, 2020 at 9:48 am

        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!

        Reply
        • Vishal says

          July 7, 2020 at 5:46 pm

          Hey Ashton, Please let me know the error.

          Reply
  9. Hoàng says

    October 29, 2019 at 2:15 pm

    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

    Reply
    • Hoàng says

      November 10, 2019 at 1:34 pm

      list=[22,25,26,32,41,35,13,16,21]

      import random
      new_list=random.sample(list[0:],3)
      import statistics
      statistics.mean(new_list)
      j=statistics.mean(new_list)
      if round(j)==20:
      	print(new_list)
      

      # program run slowly
      # Do you have a better way? Thanks

      Reply
  10. chand says

    March 13, 2019 at 8:44 am

    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.

    Reply
  11. VED PRAKASH says

    October 20, 2018 at 9:44 pm

    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.

    Reply
    • Vishal says

      October 20, 2018 at 11:18 pm

      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.

      Reply
      • Chitra Tanasap says

        July 20, 2020 at 9:39 am

        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

        Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Basics
TweetF  sharein  shareP  Pin

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com