(Sum the digits in an integer using recursion) Write a recursive function that computes the sum of the digits in an integer. Use the following function header:
def sumDigits(n):
For example, sumDigits(234) returns 2+3+4 = 9 Write a test program that prompts the user to enter an integer and displays its sum.
A test program that prompts the user to enter an integer and displays its sum:
Code :
def sumDigits( n ): #defining a function sumDigits
if n == 0: #check whether n is equal to 0 are not
return 0 # if yes,return 0
return (n % 10 + sumDigits((n // 10))) #else return sum of its digits
num = int(input("enter an integer:")) #take input num value
result = sumDigits(num) #using sumDigits function
print("Sum of digits in",num,"is", result) #print the sum
Output:
enter an integer:234
Sum of digits in 234 is 9
enter an integer:0
Sum of digits in 0 is 0
enter an integer:6455
Sum of digits in 6455 is 20