PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
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)
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:  55

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

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

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

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

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]]

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)

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

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Python Basics

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 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Posted 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 Object-Oriented Programming
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

All Python Topics

Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time 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.

Explore Python

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

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

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, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com