w3resource

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:

Contribute your code and comments through Disqus.

Previous: Write a Python program to find two elements once in a list where every element appears exactly twice in the list.
Next: Write a Python program to find whether it contains an additive sequence or not.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/challenges/1/python-challenges-1-exercise-16.php