Home > Net >  While True loop doesn't break after calling return
While True loop doesn't break after calling return

Time:12-26

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.

CodePudding user response:

You should update the value of n in each iteration as follow:

def digital_root(n):
    while True:
        digits = []
        for i in str(n):
            digits.append(int(i))
        n = sum(digits)  # add
        if n < 10:
            return n
  • Related