Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

While True loop doesn't break after calling return

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading