Need help with digit_sum

#1

This is the exercise I’m stuck on:

This is the error message i got:
Your function fails on digit_sum(434). It returns 4 when it should return 11.

I have tested the same code on a python IDE and it worked so i don’t understand what the issue is here. Please help.

``````
**my code:**

total = 0
import math
def digit_sum(n):
global total
num = n
while num > 10:
num = num/10
while num - math.floor(num) != 0:
floored = math.floor(num)
total = total + floored
num = num - floored
num = round(num, 2)
num = num * 10
total = total + num

``````

#2

seems you IDE runs python3, in which it runs fine, but codecademy runs python2

python3 is not backward compatible with python2, and changes where made to the division behavior, this also influenced the math module.

You would have to look at the changes made to the math modules between python2 and python3

#3

Thank you so much! Sorry to bother you so much but i looked up the differences and changed my code. now it looks like this (it has proper identation as above and the only changes are the decimal points and use of >= insead of >):

total = 0
import math
def digit_sum(n):
global total
num = n
while num >= 10.0:
num = num/10.0
while num - math.floor(num) != 0:
floored = math.floor(num)
total = total + floored
num = num - floored
num = round(num, 2)
num = num * 10.0
total = total + num

I managed to overcome the last error but the new error message says:
Your function fails on digit_sum(1000). It returns 12.0 when it should return 1.

but i can’t seem to understand why this would happen. Thank you so much,again, for your help!

#4

declaring total outside the function will cause total to accumalate data when calling the function multiply times

#5

Oh okay. Thank you so much!

#7

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