Learn about Python Program to Find Sum of Digits using Recursion in the below code example. Also, refer to the comments in the code snippet to get a detailed view about what’s actually happening.
Contents
Python Program to Find Sum of Digits using Recursion
The below program finds the sum of digits using a recursive approach.
# program to compute sum of digits in number using recursion
# recursive function
def ComputeSum(num):
return 0 if num == 0 else int(num % 10) + ComputeSum(int(num / 10))
# input from user
num = int(input('Enter a number: '))
# function call
print('Sum of digits in number =', ComputeSum(num))
Output:
Enter a number: 234
Sum of digits in number = 9
Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.
Similar Code : Sum of Digits using Function in Python