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.

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))

Sample 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