[rookie SOS]digit_sum exercise


#1



https://www.codecademy.com/zh/courses/python-intermediate-en-rCQKw/0/4?curriculum_id=4f89dab3d788890003000096#


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


#2

in order to validate your code, the exercise calls the function multiply times (just the function). Because your dig doesn't get set to an empty list (it is outside the function), there might be leftovers from earlier function calls

On your local machine, you call the whole program/script. Which is why it works in your local machine


#3

Hello guy.....
thanks so much...I thought I got what u mean...if I put the dig=[] outside the function , the last time result will be left in it....so when I ran the second time... the result is wrong....
I tested it on my local machine ... if call the function twice with different values....the result is totally wrong...

Thanks so much guy!


#4

because dig doesn't get set to an empty list, you get a serious problem. The multiply function calls happen in the lesson behind the scenes, but they are still there. Good to see you understand :slight_smile:


#5

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