digit_sum - Why does the 'if' make it not work?


#1


If I use this code, I pass the exercise:

def digit_sum(n):
    result = 0
    for num in str(n):
        result += int(num)
    return result


But if I use an 'if' statement to check if it's a positive number:

def digit_sum(n):
    result = 0
    if n == int and n > 0:
        for num in str(n):
            result += int(num)
    else:
        print "Not a number or < 0."
    return result

An error shows up: Oops, try again. Your function fails on digit_sum(434). It returns 0 when it should return 11.
Why does this happen?


#2

@sircommoner: That's because you're trying to compare an argument with a type and such won't be true.
If you stop to think about it, comparing those two things doesn't really make sense, considering the way it is.

If you want to check the type, use the function type() with the argument you want to test.

It should work now.

P.S.: pay attention to that return statement inside your loop/conditional instruction.


#4

Ooooh. Thanks, I forgot about 'type()'