1

I am trying to write a function that takes any number of arguments and then sums them using recursion ( I am not using the built in sum function. I am assuming arguments will be int. )

But my base case doesn't stop it from recursing! Any hints?

def sum_all(*args):
 if args == ():
    return 0
 else:
    return args[0] + sum_all(args[1:])

1 Answer 1

7

You need to expand the args in your recursion, and not args would be sufficient for the test:

def sum_all(*args):
    if not args:
        return 0
    return args[0] + sum_all(*args[1:])
                             ^

Python 3 also added some new syntax that allows you to unpack *args, e.g.:

def sum_all(*args):
    if not args:
        return 0
    a, *b = args
    return a + sum_all(*b)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.