# Function Failure

#1

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

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

``Replace this line with your code.``

#2

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``````

#3

4 posts were split to a new topic: Blurring

#4

Thanks mtf

#5

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