I am not sure why I can not return the sum(result)? I used print statements to check my work and the algorithm works with the print statement but the console won't accept return sum(result). Is there some limitation to the result function I'm not understanding?

result = []

def digit_sum(n):
    s = str(n)
    for char in s:
    #print result
    return sum(result)


You cannot use integer methods like sum(). On a string,


In this case you can use int() on a string because the string is a string of a number. The int() is a python built in function that converts a string of a number into an integer.

source: Converting Strings with int()

I figured out the problem was I had a global variable, result, that I did not declare using the global keyword in my function.


Yes I know that but in your code you converted into a string just for iteration. Unnecessary. :slight_smile:


He his using sum() on a list, which is legit. The problem is that the empty list is defined in global scope so never gets reset to empty on each call to the function.

Define result = [] inside the function, before the loop.

But valid. The code converts str to int as expected.