NoDinner NoDinner - 1 year ago 209
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......

def digit_sum(n):
for i in u:
for number in dig:
return s

Answer Source

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.

If you do dig = [] inside the function, it creates a new, local list - it isn't being changed each time, it's a new empty list for each rotation.

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.)