Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Recursion Functions

Recursive function to calculate sum of digits - Python Program

Example 1 :

def sum_of_digits(n): """Sum digits of a number recursively.""" if n == 0: return 0 return n % 10 + sum_of_digits(n // 10) print(sum_of_digits(1234))

Output

 
OUTPUT  :
10

Example 2 : Advanced Program

def recursive_sum_of_digits(n): """ Calculates the sum of digits of a non-negative integer using recursion. Args: n: The non-negative integer. Returns: The sum of its digits. """ # Base case: if the number is 0, the sum of its digits is 0. if n == 0: return 0 # Recursive case: add the last digit to the sum of digits of the remaining number. else: return (n % 10) + recursive_sum_of_digits(n // 10) # Example Usage: number = int(input("Enter a number : ")) sum_digits = recursive_sum_of_digits(number) print(f"The sum of digits of {number} is: {sum_digits}") number_two = 789 sum_digits_two = recursive_sum_of_digits(number_two) print(f"The sum of digits of {number_two} is: {sum_digits_two}")

Output

 
OUTPUT  :
Enter a number  : 12345
The sum of digits of 12345 is: 15
The sum of digits of 789 is: 24