Math domain error in digit_sum challenge


I get thrown a math domain error with the code below when it's in code academy. If I run it in a normal python environment then it works perfectly. I'm wracking my brain to figure out what I'm doing wrong here.

For the record, I know the commented version is much much simpler. But I'm still curious as to what I'm doing wrong with the more complicated approach.

def digit_sum(n):
    sumof = 0
    n = str(n)
    for x in range(len(n)):
        sumof = sumof + int(n[x])
    return sumof

import math

def digit_sum(n):
    sumof = 0
    digits = 0
    digits = int(math.log10(n)) + 1
    print digits #debug
    for x in range(digits):
        sumof = sumof + n // (10**x) % 10

    return sumof


You would have to test with the same input as was used when the math domain error was raised. Looks like you changed several things and attributed the difference in behaviour to the wrong change.


Did you happen to input 0 for n? What if the SCT tests this value?


Wow, I can't believe I overlooked this and didn't test 0 on my own. I added an exception for it and it runs perfectly. Thanks for bringing that to my attention.


Found that the error was coming from Code Academy when it ran n as 0. Too simple, I'm kicking myself. Thanks for the input.


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