w3resource logo


Python Exercises

Python Challenges: Add the digits of a positive integer repeatedly until the result has a single digit

Python Challenges - 1: Exercise-16 with Solution

Write a Python program to add the digits of a positive integer repeatedly until the result has a single digit.

Input : 48
Output : 3

For example given number is 59, the result will be 5.
Step 1: 5 + 9 = 14
Step 1: 1 + 4 = 5

Explanation :

Python: Add the digits of a positive integer repeatedly until the result has single digit

Sample Solution :-

Python Code :

def add_digits(num):
        return (num - 1) % 9 + 1 if num > 0 else 0

print(add_digits(48))
print(add_digits(59))

Output :

3                                                                       
5

Flowchart:

Python Flowchart: Add the digits of a positive integer repeatedly until the result has single digit

Python Code Editor:

def add_digits(num):
        return (num - 1) % 9 + 1 if num > 0 else 0

print(add_digits(48))
print(add_digits(59))

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.