Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
735 views
in Technique[技术] by (71.8m points)

python - How to make loop repeat until the sum is a single digit?

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 number 2345 has the sum 2+3+4+5 = 14 which is not a single digit so repeat with 1+4 = 5 which is a single digit.

This is the code I have so far. It works out for the first part, but I can't figure out how to make it repeat until the sum is a single digit. I'm pretty sure I'm supposed to nest the code I already have with another while statement

n = int(input("Input an integer:"))
sum_int=0  
while float(n)/10 >= .1:   
    r= n%10
    sum_int += r
    n= n//10   
    if float(n)/10 > .1: print(r,  end= " + ") 
    else: print(r,"=",sum_int)

this is a sample output of the code

Input an integer: 98765678912398

8 + 9 + 3 + 2 + 1 + 9 + 8 + 7 + 6 + 5 + 6 + 7 + 8 + 9 = 88

8 + 8 = 16

1 + 6 = 7

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This should work, no division involved.

n = int(input("Input an integer:"))
while n > 9:
    n = sum(map(int, str(n)))
print(n)

It basically converts the integer to a string, then sums over the digits using a list comprehension and continues until the number is no greater than 9.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...