4/15 - It returns the right result but the site says it is wrong


#1



data = []
def digit_sum(n):
    n = str(n)
    for char in n:
        char = int(char)
        data.append(char)
    print sum(data)
digit_sum(434)

It says,

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


#2

Initialize data inside the function so it is empty each time the function is called. By setting it in global scope, previous results are still in the list on subsequent calls to the function.

Instead of printing the result, take your cue from the error message, and return it.

print (digit_sum(434))     # 11

#3

It worked this way but so as the other. Why CodeAcademy didn't accept the first one?


#4

Because before it did not return a value, so None is what the SCT saw.

Had it returned a value, it would still have failed due to where the data list is defined. The SCT would have seen 22 as a result (434434). It's important to consider where best to define variables. Usually inside the function is best.


#5

Oh, got it. Thanks!!


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.