Prompt: Write a program that adds all the digits in an integer. If the resulting sum is more than one digit, keep repeating until the sum is one digit. For example, the numb
def add_digits(num):
return (num - 1) % 9 + 1 if num > 0 else 0
A simple, elegant solution.
You don't need to convert your integer to a float here; just use the divmod() function in a loop:
def sum_digits(n):
newnum = 0
while n:
n, digit = divmod(n, 10)
newnum += digit
return newnum
By making it a function you can more easily use it to repeatedly apply this to a number until it is smaller than 10:
n = int(input("Input an integer:"))
while n > 9:
n = sum_digits(n)
print(n)