Sum of Digit of a Number using Recursion in Python

This is a Python Program to find the sum of the digits of the number recursively.

Problem Description

The program takes a number and finds the sum of the digits of the number recursively.

Problem Solution

1. Define a recursive function which takes a number as the argument.
2. Take a number from the user and pass it as an argument to a recursive function.
3. In the function, put the base condition that if the number is zero, return the formed list.
4. Otherwise, get each digit and append it to the list.
5. Find the sum of the digits in the list outside the function.
6. Print the total sum.
7. Exit.

Program/Source Code

Here is source code of the Python Program to find the binary equivalent of a number recursively. The program output is also shown below.

l=[]
def sum_digits(b):
    if(b==0):
        return l
    dig=b%10
    l.append(dig)
    sum_digits(b//10)
n=int(input("Enter a number: "))
sum_digits(n)
print(sum(l))
Program Explanation

1. A recursive function is defined which takes a number as the argument.
2. A number is taken from the user and passed as an argument to a recursive function.
3. In the function, the base condition is that if the number is zero, the formed list is returned.
4. Otherwise, each digit is obtained using a modulus operator and appended to the list.
5. The function is then called with the number taken from the user and the sum of the digits in the list is found out.
6. The total sum is printed.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
Enter a number: 135
9
 
Case 2:
Enter a number: 546
15

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

Note: Join free Sanfoundry classes at Telegram or Youtube

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.