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

2

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

I made the following code but it is giving None :

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


print(somadig(120))
    
asked by anonymous 10.12.2018 / 15:42

1 answer

5

You are not treating the output correctly. When n reaches 0 it should return 0, otherwise it should make the account and cause recursion. You have variables and too many steps in the code, work with the sum directly instead of saving in variable and pass again, simplifying:

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

print(somadig(120))

See running on ideone . And no Coding Ground . Also I put GitHub for future reference .

Your given None because if the condition of if is false it does not pass return , so it returns nothing.

    
10.12.2018 / 15:46