How to use 'while' command with modulo and floor divide?


#1


I'm getting an infinite loop when I try to solve this problem using 'while' and incorporating the modulo + floor divide method. I can do it using 'for' (see code below), but using very similar code doesn't work with while. It's telling me I get an infinite loop - why is this the case when I have included "num = int(num) // 10", which should take off the last digit and decrease len(num) by 1?


# code works with 'for'

def digit_sum(n):
    count = 0
    num = str(n)
    for i in range(len(num)):
        count += (n % 10)
        n = n // 10
    return count

# similar code does not work with 'while'

def digit_sum(n):
    count = 0
    num = str(n)
    while len(num) > 0:
        count += (int(num) % 10)
        num = int(num) // 10
        num = str(num)
    return count


#2

the beauty of the modulo operator and floor division is that you don't need to convert to string. At certain point, n will simply be zero.

so then you can just do:

while n > 0:

#4

Oh, duh, thanks so much for your answer. This code is much simpler and works:

def digit_sum(n):
    count = 0
    while n > 0:
        count += (n % 10)
        n = n // 10
    return count

I'm still not sure why the len(n) method didn't work, but this is more straightforward.


#5

your current program is shorter and more efficient. (you saved your self on a lot string/integer casting.

well, this line:

num = int(num) // 10

would make num 0 at some point. then you cast 0 to a string so you get: "0", which has a length of 1, so this condition:

len(num) > 0

never becomes false


#6

Oooh, that makes a lot of sense - thanks again!


#7