4/15 Why wouldn't this code work for this problem?


#1

Can someone explain why this wouldn't work in 4/15?

def digit_sum(n):
for x in str(n):
x = int(x)
return sum(x)


#2

If we break it down what your code is doing is:

def digit_sum(n):        # Takes n as a parameter (with the assumption its an integer)
    for x in str(n):     # for each character in the string representation of the n integer
        x = int(x)       # take the integer representation of that character and reassign it to x
    return sum(x)        # return the sum of this one integer

The Python Documentation for sum() tells us that what we call it on needs to be an iterable and trying to call it on x while it is a single integer doesn't work.

A quick search in this forum brings up this post and having a look at it will surely help you :smile: