I'm trying to write a function that would take an integer, divide it into digits, sum them up, and if the sum is >=10, loop through the process until I get a single-digit sum. Could anyone tell me why my 'while True' loop isn't breaking:
def digital_root(n):
while True:
digits = []
for i in str(n):
digits.append(int(i))
if sum(digits) < 10:
return sum(digits)
I'm not really looking for an optimal solution, I just want to know why this doesn't work.
def digital_root(n):
while True:
digits = []
for i in str(n):
digits.append(int(i))
print(digits)
if sum(digits) < 10:
return sum(digits)
n=sum(digits)
You reset the digits
variable in each iteration, so you never reach the exit condition. Maybe you want to move digits = []
before the while
?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.