[Tutor] product of all arguments passed to function call

Alan Gauld alan.gauld at yahoo.co.uk
Mon May 31 06:19:19 EDT 2021


On 31/05/2021 10:56, Manprit Singh wrote:
> Dear sir ,
> Consider a problem where i have to find the product of all arguments passed
> to function call , where the function must be capable of accepting any
> number of arguments : My approach will be as follows :
> 
> def product(x, *y):
>     for ele in y:
>         x *= ele
>     return x

You solution works for the case where at least 1 argument is passed.
What if none are passed? A small change suffices:

def product(*x):
    result = 1 if x else 0
    for n in x:
      result *= n
    return result

If you don't like returning zero for an empty list you could
raise an exception instead - ValueError perhaps?.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list