Strange behavior - digit_sum


#1



y = []

def digit_sum(n):
    n = str(n)

    for x in n:
        x = int(x)
        y.append(x)

    for z in y:
        z = sum(y)
    return z

print digit_sum(434)

The error says: Oops, try again. Your function fails on digit_sum(434). It returns 22 when it should return 11.

However, in fact the function returns exactly 11. :slight_smile:


#2

Hi @yavor_01,

You have this outside your function ...

y = []

Is that where it should be?

As a test, call your function more than once in your code, and observe the output.

Does this actually need to be inside a for loop? ...

    z = sum(y)

#3

You are absolutely right! :slight_smile:

Thank you!


#4