While function not reiterating


#1

Heya

I can't seem to figure out why my While clause isn't looping

>>> 
def digit_sum(n):
    if n > 0:
        nsum = 0
        print(nsum)
        while len(str(n)) > 0:
            nsum += n % 10
            print(nsum)
            n = n // 10
            print(n)
            return n
    else:
        print("Please enter a positive number")

        
>>> digit_sum(434)
0
4
43
43

Is loops once and exits even though len(str(n)) should be > 0 after 1st loop


#3

a function ends the moment a return keyword is reached, so your function ends in the first run/iteration loop

careful, you have an infinity loop. at the end, n has a value of zero, which still has a length greater then zero


#5

good that realized this yourself, way more valuable then when i would tell you this, i was hinting at it


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.