Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 22 Online
OpenStudy (anonymous):

why do functions save variable definitions when using python from the command line?

OpenStudy (anonymous):

I'm using the python environment in a Linux terminal, and I keep getting errors when I try to use functions twice, because somehow the function retains the definitions of variables from previous calls. This doesn't happen when I run the same functions in IDLE on my Mac. Any ideas?

OpenStudy (anonymous):

Example?

OpenStudy (anonymous):

def test (inputString, testList = []): for x in inputString: testList += x, return inputString[len(testList) - 1] Actually, it's happening on my Mac too. I think there's something I don't understand about default variables. the function above tests the problem I'm having. It's supposed to return the last character in the string by assigning testList to the empty list by default (the function I was working on when I found this problem included a default variable, so I wanted to include one), then to add each character in the inputString to the list, measure the length of the list, and try to return the last position from the string. What happens is that if I run it once, using test('fgzsjtztj') it works. If I run it again with the same input, it gives me an indexerror saying that the inputString string index is out of range. I can see that the letters from the previous inputString are still in the default for testList.

OpenStudy (anonymous):

I believe this link addresses your question: http://boodebr.org/main/python/tourist/mutable-obj-as-default-arg

OpenStudy (anonymous):

That is it exactly. Thanks!

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!