4. digit sum (Why is my code wrong?)


#1



digits = []

def digit_sum(n):
    for x in str(n):
        digits.append(int(x))
    print sum(digits)

Python tells me that my function returns none. However, when I run the function myself it returns the correct answer. I feel like I'm going crazy!

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


#3

Hello @pythondoodman,

for a function to return something, you have to use the return keyword. For instance,

def random_function(n):
   return n * 3

You also have to define digits as an empty list like this: digits = [] Try this and you'll be good to go


#4

I already have digits defined as an empty list?

Also I changed "print" to "return" and it gives me this error.

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


#5

The issue is with where the list is defined. As a global it will accumulate as the program is called up repeatedly. Define it inside the function (locally) so it starts fresh with each successive call.


#6

Awesome thank you!! This worked. Let me see if I'm understanding this right...
if "digits = []" is not nested in the function, the list will continue to grow with new numbers on each iteration of the loop? Therefore, putting it inside of the function causes it to reset to an empty list every time?


#7

That is correct. When it is outside of the function, how does it get reset without a special statement? Simpler to define it where it is used, and not bring it in from the outside.

What you have now is a pure function. All values are internal or given in the parameters. The outcome will always be the same when the inputs are the same.