Calculate sum in python

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

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

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

  • The sum of the first n natural number = n * (n+1) / 2
  • the average of first n natural number = (n * (n+1) / 2) / n
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.

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 wp-block-preformatted">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 wp-block-heading" >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.

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

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

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

Источник

Python sum() Function

The sum() function returns a number, the sum of all items in an iterable.

Syntax

Parameter Values

Parameter Description
iterable Required. The sequence to sum
start Optional. A value that is added to the return value

More Examples

Example

Start with the number 7, and add all the items in a tuple to this number:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Читайте также:  Css selector class and tag
Оцените статью