4. digit_sum - I don't get it?


#1

I'm trying to follow along with the lesson, and I wrote this out:

def digit_sum(n):
    totalsum = 0
    while n > 0:
        digit = n % 10
        totalsum = totalsum + digit
        return totalsum
        n = n // 10
    print totalsum

But it gives me this error:

Oops, try again. Your function fails on digit_sum(434). It returns 4 when it should return 11.

What am I doing wrong? I've been relooking it over and over for over a day, and I can't think of what went wrong??


#2

Hi @sosoeuso ,

Your posted code is missing the function header. It probably looks like this ...

def digit_sum(n):

EDIT July 31, 2016: @sosoeuso has corrected the omission described above.

You have this in the for loop ...

return totalsum

That returns a result during the first iteration of the loop, terminating function execution before it has processed all the digits. Only the right-most digit gets included in the total.

To remedy the problem, take that return statement out of the loop and replace the print statement with it. In that new position, it will return the result after the loop has completed all its iterations.

Then, to call the function and see some results, you can do something like this ...

print(digit_sum(234)) # should print 9
print(digit_sum(787)) # should print 22
print(digit_sum(1234)) # should print 10

#3

Oh, shoot, my bad, I forgot to copy the first line. I'll fix it in the OP.

And thanks, that actually made the code work properly!


#4

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