Function Failure


Hi Everybody,

My code returns this error "Oops, try again. Your function fails on digit_sum(434). It returns 8 when it should return 11."

Here's the code....I've seen other solutions, but wish to know what is wrong with my approach. Thanks for your help!

def digit_sum(n):
for i in range(n):
i = n % 10
a = n / 10
n = int (a)
i += i
print n
return i

Replace this line with your code.


This loop construct does not fit the math you are attempting.

If you wish to use range(), then add up the values at each index.

    total = 0
    m = str(n)              # convert number to an iterable
    for i in range(len(m)):
        total += m[i]

Using the math approach, we would use a while loop and operate directly upon n.

    total = 0
    while n > 0:
        total += n % 10    # add last digit
        n //= 10           # floor divide to remove that digit


4 posts were split to a new topic: Blurring


Thanks mtf :relaxed:


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