summing_numbers_in_python

Python Example 2 – Summing Numbers

Hello World, Welcome to projectsplaza.com. In this tutorial, we will create a custom python function to show the sum of the provided numbers. This function takes a sequence of numbers and shows the sum of those numbers. This exercise helps you to understand numbers and function design.


The custom_sum function is a simple example of how we can use python “splat” operator (*) to allow a function to receive any number of arguments. We will preface the name numbers with *, we are telling python that this parameter should receive all of the arguments.


The splat(*) operator is especially useful when you want to receive an unknown num-
ber of arguments.

def custom_sum(*numbers):
    result=0
    for number in numbers:
        result+=number
    return result

print (custom_sum(10,20,40,50))

The built-in version of the sum takes an optional second parameter, which is used as a starting point for summing. for example; sum([2,3,4],5) return 14 because the sum of the first argument is the starting number of this function. if the second argument is not provided then it will be 0.

Leave a Reply

Your email address will not be published. Required fields are marked *