NoDinner - 4 months ago 29x
Python Question

# codecademy Practice Makes Perfect digit_sum

The purpose is Write a function called digit_sum that takes a positive integer n as input and returns the sum of all that number's digits.

For example: digit_sum(1234) should return 10 which is 1 + 2 + 3 + 4.

(Assume that the number you are given will always be positive.)

Your function fails on digit_sum(1000). It returns 12 when it should return 1.

If I put the dig=[] upper on the def digit_sum, the course occurred alarm that "digit_sum(1000) result is 12 instead of 1" , but I ran this program on my local notepad+powershell, it ok , the result is right.

after that I put the dig=[] into the first line of function , then it worked normally .

I didn't get 2 points....

1. What's the difference between "dig=[]" inside/outside the function

2. if the "dig=[]" outside the function is wrong , why I can ran it successfully on my local....?

Thanks for guys to help me......

``````dig=[]
def digit_sum(n):
u=str(n)
for i in u:
dig.append(i)
s=0
for number in dig:
int(number)
s=s+int(number)
return s
``````

So the difference between inside/outside is locality. When you put `dig` outside, you create a global list. From there, you're constantly appending to that- the list is never cleared! So if I run `digit_sum(1234)`, I properly get 10. If I immediately thereafter run `digit_sum(1000)`, `dig==['1','2','3','4','1','0','0','0']` which will then add all those and mess up.
The reason you're getting it correctly sometimes is because the function has side effects, so order of calling and history of calling matters. Try to avoid side effects of functions- either don't alter a list, or copy the list>alter that copy>`return` the copy if you want to assign the new list (or just work with the new list.)