-1

Here in this program, I tried to understand but couldn't get completely. How is this recursive function doing the sum and returning total sum of this? Please explain me in detail?

# Recursive Python3 program to
# find sum of digits of a number
# Function to check sum of
# digit using recursion

def sum_of_digit( n ):
    if n < 10:
        return n
    return (n % 10 + sum_of_digit(n // 10))    # how this is working ?


num = 12345
result = sum_of_digit(num)
print("Sum of digits in",num,"is", result)
Emi OB
  • 2,814
  • 3
  • 13
  • 29

1 Answers1

1

The best way to understand a recursive function is to dry run it.

First you need to understand what n % 10 mean is. this means the remainder of a n when divided by 10. In this case when we divide 12345 by 10 , we get 5 as remainder. so n % 10 part of code becomes 5.

Now, the second part is n//10 which gives you 1234 that are remaining digits. Applying the same function again will give you 4 + sum_of_digit(123) and so on.

Even if this do not clear your confusion try, running this code on paper with some small number.

glitch_123
  • 139
  • 12