Recursive function that returns the sum of the digits of a number

Asked

Viewed 1,458 times

2

I need to create a recursive function that takes a number n integer and returns the sum of the digits of this number.

I made the following code but it’s giving None:

def somadig(n, s = 0):
    if n > 10:
       d = n%10
       s += d
       return somadig(n//10,s)


print(somadig(120))
  • In this case the result would be 3?

1 answer

5


You are not treating the output correctly. When n reach 0 must return 0, otherwise you must make the account and cause recursion. There are too many variables and steps in the code, work with the sum directly instead of storing in variable and pass again, simplifying:

def somadig(n):
    if n == 0:
        return 0
    else:
        return (n % 10) + somadig(n // 10)

print(somadig(120))

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

His giving None because if the condition of if is false does not pass through a return, so it returns nothing.

  • Thank you, I didn’t know you could pass a sum expression with the function

  • It can pass any expression, and this is generalized in the language, in fact are few places where it does not fit any expression, but where it fits one, can always any.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.