简体   繁体   中英

function (sum_it_up) that takes any number of parameters and returns to sum

How to write a function (sum_it_up) that takes any number of parameters and returns to sum?

For instance this should print 22:

total=sum_it_up(1,4,7,10)
print(total) 

Solution:

def sum_it_up (a,b,c,d):
print("The total is {0}".format(a+b+c+d))

sum_it_up(1,4,7,10)
sum_it_up(1,2,0,0)

The above solution is missing the return statement. Any ideas? Thanks!

As @georg suggested, you should use *args to specify a function can take a variable number of unnamed arguments.

args feeds the function as a tuple. As an iterable, this can be accepted directly by Python's built-in sum . For example:

def sum_it_up(*args):
    print('The total is {0}'.format(sum(args)))

sum_it_up(1,4,7,10)  # The total is 22
sum_it_up(1,2,0,0)   # The total is 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM