Function that adds all values inputed

e-papa 0 Tallied Votes 487 Views Share

We all know that the sum() function in python only takes two arguements, so i created a function in python that will take any number of arguements and add them together, just like the sigma letter in greek.
Awaiting your replies on this one.

#---------------------------------------------------#
"""-----------------ADEGOKE OBASA-----------------"""
"""------------adegokeobasa@yahoo.com-------------"""
"""--This functions adds all the values inputed---"""
def sumall(*args):
    """This function takes max arguements
        and sums all the arguements"""
    leng=len(args)
    n=1
    temp=args[n-1]
    while n!=leng:
        temp+=args[n]
        n+=1
    return temp

#example
#print(sumall(10,10,1,10,10,10,10,10))
#>>>
#71
e-papa 13 Posting Pro in Training

What to see your replies, experts in the house.

TrustyTony 888 pyMod Team Colleague Featured Poster
def sumall(*items):
    return sum(sum(item) if item.hasattr('__iter__') else item for item in items)

To do deep sum.

Unfortunately unable to test in my mobile.

sum((10, 29, 59))
# or define
def sumall(*seq): return sum(seq)

Maybe simpler to do what you did.

e-papa 13 Posting Pro in Training

I'm sorry but I don't yet really understand classes and objects yet, that's why I'm taking it slowly, and make sure I understand the basics before i dive into the classes, but will definitely give it a try as soon as i understand classes and objects.
Thanks, a lot tonyjv

snippsat 661 Master Poster
def myfunc(*args):
    return sum(args)

print myfunc(10,10,1,10,10,10,10,10) #71
e-papa 13 Posting Pro in Training

WoW, now that's what i'm saying, never knew it could be this easy, i guess when you are just starting you always want to believe things have to be complex and long.
Well you've thought me something else, as a programmer you have to think not just of a way to solve the problem, but of a way to solve it as fast as possible.
Thanks again.

TrustyTony 888 pyMod Team Colleague Featured Poster

As somebody said ones one quote on Gribouillis' code something like "Beauty is not how complex thing is but when nothing can be any more taken out."

e-papa 13 Posting Pro in Training

Good one, tonyjv, always making a point.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.