4/15... Why isn't my code working?


#1

def digit_sum(n):
result=0
c=str(n)
for i in len(str(n)):
result=result+int(c[i])
return result


#2

As to why your code does not work,

for i in len(str(n)):

You are converting it to a string then asking the len of the string which is an int object which cannot be iterated.

This is what you need to have.

for i in str(n):

Then change the next line to,

result.append(int(i))

Then the final line should be

return sum(result)

Using list comprehension,

def digit_sum(data):
    """
    This function converts the data into a string, then iterates over it adding it to
    a list. It then converts it back into an int when it adds it to the list. After that 
    it uses the built-in function sum() to add the list together.
    """
    return sum([int(digit) for digit in str(data)])