4.Digit Sum problem : infinite loop


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/4?curriculum_id=4f89dab3d788890003000096#


It seems that my code contains an infinite loop which I have failed to recognize for a whole afternoon.


I have already went through other discussion about this task, so I am not looking for a solution to get to the next session. If anyone has an idea about where I failed please don't hesitate to share your insight. Thank you.


def digit_sum(n):
    digitsum = 0
    p = 1
    while n % (10**p) > 0:
        digitsum += (n % (10**p) - n % (10**(p-1))) / 10**(p-1)
        p += 1
    return digitsum


#2

Before you do anything test that there are values for n and p that cause your loop to stop.

Then you might want to use print statements to observe how they change as your loop runs. (Observe what it does differently from what you want it to be doing, just guessing won't get you the information you need or you wouldn't be having the problem in the first place)


#3

Perhaps you haven't made a mistake involving an infinite loop before, but even if I add a print statement after the main part of my code, it wouldn't be shown since the code cannot be executed.


#4

An infinite loop means it's doing nothing but executing.
Now you're saying it isn't executing at all. That would mean that you don't have an infinite loop.

Which is it?


#5

Sorry for my bad grammar. What I mean is that it couldn't end executing and thus never finally executed.


#6

Do you mean it doesn't terminate? That's not a problem though, you can still print. It'll get killed off eventually.
You can also return early if you want to keep the output more manageable.


#7

I solved my problem after reexamining my code. Missed it on the while condition.

def digit_sum(n):
    digitsum = 0
    p = 1
    while n / (10**(p-1)) > 0:
        digitsum += (n % (10**p) - n % (10**(p-1))) / (10**(p-1))
        p += 1
    return digitsum

Thank you anyway.


#8

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