Question

Write a recursive function in Python to find the sum of digits of a number. Name the function sum_of_digits. The function should use recursive algorithm (calling itself). The function should print out the sum of all the digits of a given number. For example, sum_of_digits(343) should have a output of 10. Marks will be deducted if you do not follow strictly to the instructions.[3]: N 1 def sum_of_digits(n): HNM in sum_of_digits (343) Out[3]: 10

0 0
Add a comment Improve this question Transcribed image text
Answer #1

PROGRAM:

# Definition of sum_of_digits() function
def sum_of_digits(n):
    if(n==0):
        return n
    else:
        # rem = n%10
        # div = n/10
        # return rem + sum_of_digits(div)
        return n%10 + sum_of_digits(n/10)

# Taking input number from user
number = int(input('Enter a number: '))
# Calling sum_of_digits() function and storing the return value in result
result = int(sum_of_digits(number))
# Printing the result
print("Sum of digits of " + str(number) + " is " + str(result))

Please refer to the following screenshot of the program for indentation of the code:

SAMPLE OUTPUTS:

# Definition of sum_of_digits() function def sum_of_digits (n): if(n==0): return n else: rem = n$10 div = n/10 return rem + sum_of_digits (div) PUREBOJU # Taking input number from user number = input ( 'Enter a number: ') # Calling sum_of_digits() function and storing the return value in result result = sum_of_digits (number) # Printing the result print("Sum of digits of " + str(number) + " is " + str (result))

Enter a number: 343 Sum of digits of 343 is 10 Process finished with exit code 0

Enter a number: 12396 Sum of digits of 12396 is 21 Process finished with exit code 0

Add a comment
Know the answer?
Add Answer to:
Write a recursive function in Python to find the sum of digits of a number. Name...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT