-4

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!

Kouder
  • 33
  • 8
tester787
  • 109
  • 1
  • 1
    That solution isn't valid anyways, since it doesn't take "any number of parameters". And what specifically do you need help with in adding a return? – Carcigenicate Feb 18 '18 at 01:17
  • 2
    Your proposed solution doesn't scale. What if I want to sum _five_ numbers? six? The requirements said "any number of parameters." **(1)** Look into [`*args`](https://stackoverflow.com/questions/3394835/args-and-kwargs) **(2)** Since I'm assuming you can't use the built-in `sum`, you need to formulate a way to sum a list of numbers (_hint_: you'll need a loop). – Christian Dean Feb 18 '18 at 01:17
  • Suggested reading: https://stackoverflow.com/questions/919680/can-a-variable-number-of-arguments-be-passed-to-a-function https://stackoverflow.com/questions/7129285/why-would-you-use-the-return-statement-in-python – georg Feb 18 '18 at 01:19

1 Answers1

0

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
jpp
  • 159,742
  • 34
  • 281
  • 339