0

I want bo create a function which returns sum of all passed arguments.

I found similar problem on forum, but It doesn't work with last case.

def sum_all(*args):
    sum = 0

    for num in args:
        if not str(num).isdigit():
            return False
        else:
            sum += int(num)
    return sum

This code work with first and second case, but return false on third case.

sum_all(2,-3)
# -1
sum_all([3,4,5])
# 12
sum_all(1,2,[3,4,5])
# false 

How can i make it work? To make it return 15 in last case? Thanks!

Barmar
  • 741,623
  • 53
  • 500
  • 612
Wazowski
  • 27
  • 4

2 Answers2

2

In case of a list, just call the function recursively, example:

def sum_all(*args):
  sum = 0
  for num in args:
    if type(num) is list:
      sum += sum_all(*num)
    else:
      sum += int(num)
  return sum
Simona
  • 349
  • 2
  • 8
1

Can use this

def sum_all(*args):
    s = 0
    for a in args:
        if type(a)==list:
            s+=sum(a)
        else:
            s+=int(a)
    return s
print(sum_all(2,-3))
print(sum_all([3,4,5]))
print(sum_all(1,2,[3,4,5]))
theCoder
  • 34
  • 5