Digit_sum, Printed output is returning as correct but the returned output is wrong?



The print in my function is showing the correct sum, but the return (according to my "Oops, try again" message) is wrong.

"Oops, try again. Your function fails on digit_sum(434). It returns 44 when it should return 11."

I know there are much simpler ways to solve this problem but once I got set on solving it this way I really just wanted to pursue this path.

split = []
split2 = []


def digit_sum(n):
    total = 0
    for i in str(n):
    print split
    for x in split:
    print split2
    total = sum(split2)
    print "Sum is: %s" % total
    return total
s = raw_input("Tell me your number: ")


When using raw_input() we must remember that the return is <type 'unicode'>, not <type 'int'>. This is important to note.

Passing the output of raw_input() directly to a function requires that we convert it to the expected type, at which point we are faced with making assumptions that may not be valid. This means we need to filter.

import re
def digit_sum(n):
    test = True if re.match(u'^[0-9]+$', str(n)) else False
    if test: 
        a = list(str(n))
        # more code
        return "Input Error!"

Now we have an interable in a and can proceed with the final step, summing up the list elements.

 # more code
        for i in range(len(a)):
            a[i] = int(a[i])
        return sum(a)

We have used a regular expression to match only digits, and nothing else. All other inputs will be rejected. Note the importance of importing the regular expression module without which this code will throw an error.

The power of Python is illustrated in the following example which uses a list comprehension built around the ternary expression above.

def digit_sum(n):
    return sum([int(i) for i in str(n)]) if re.match(u'^[0-9]+$', str(n)) else "Input Error!"

I don't necessarily recommend this, though, since it also has some questionable code. We only really need to match the input at the start, not repeatedly in the loop. For that reason, this is undesirable code, even though it does work. Here it is meant only as an example.