In this short tutorial, we look at different methods to find the sum() of numbers, integers, float numbers and complex numbers in Python.
Table of contents - Python Sum
- sum () function
- Sum of numbers
- Sum of numbers and a start value
- Sum of float values
- Sum of float values and integers
- Sum of complex numbers
- Creating a for loop
- Using Recursion function
- Closing thoughts
sum () function
The sum() function returns the sum of all items in an iterable. It is a Python built-in function.
There are various methods to do this. We can use Python libraries or can use other methods for the same. Let us look at them one by one.
Iterable - the values to be added. It is a compulsory field. Iterators can be lists, tuples, strings or dictionaries - basically, a group of numbers.
Start - the value to which the iterable is to be added. It is an optional field and takes the value “0” if we don’t enter any.
Sum of numbers
# using syntax sum(iterable) a = (1, 3, 5, 7, 9) b = sum(a) print(b)
Sum of numbers and a start value
# using syntax sum(iterable, start) a = (1, 3, 5, 7, 9) b = sum(a, 11) print(b)
Sum of float values
a= (10.2, 12.5, 11.8) total= sum(a) print(total)
Sum of float values and integers
a= (1, 3, 5, 7, 9, 10.2, 12.5, 11.8) total= sum(a) print(total)
Sum of complex numbers
The sum () function can add complex numbers just like it is used to do a sum of integers, float numbers or a combination of both.
s = sum([1 + 3j, 5 + 7j]) print(s) s = sum([1 + 3j, 5 + 7j], 9 + 11j) print(s) s = sum([1 + 3j, 5, 7.5 - 9j]) print(s)
(6+10j) (15+21j) (13.5-6j)
Creating a for loop
The for loop runs from the first to the last value in the declared iterable and adds the numbers one by one to the total. We create a variable that holds the sum till the end of loop, and returns the sum of all values. Here’s an example of the for loop to obtain sum when using Python.
sum = 0 for x in [1,3,5,7,9]: sum = sum + x print(sum)
Using Recursion function
The function calling itself is called Recursion. To sum numbers in python, we can declare a function to add two values, and call the same to add another value to the return value of the function. Below is an example of how we can use the recursion function.
def total(numTotal): theSum = 0 for i in numTotal: theSum = theSum + i return theSum print(total([1,3,5,7,9]))
The sum of numbers can be obtained in python using the in-build function sum (), by using for loop, or using recursive function. The easy way to sum numbers is by using the sum() function. We can also find sum of list using Python.
Top comments (0)