A community for students.

Here's the question you clicked on:

55 members online
  • 0 replying
  • 0 viewing

anonymous

  • 5 years ago

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

  • This Question is Closed
  1. anonymous
    • 5 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    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?

  2. anonymous
    • 5 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    Example?

  3. anonymous
    • 5 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    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.

  4. anonymous
    • 5 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

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

  5. anonymous
    • 5 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    That is it exactly. Thanks!

  6. Not the answer you are looking for?
    Search for more explanations.

    • Attachments:

Ask your own question

Sign Up
Find more explanations on OpenStudy
Privacy Policy

Your question is ready. Sign up for free to start getting answers.

spraguer (Moderator)
5 → View Detailed Profile

is replying to Can someone tell me what button the professor is hitting...

23

  • Teamwork 19 Teammate
  • Problem Solving 19 Hero
  • You have blocked this person.
  • ✔ You're a fan Checking fan status...

Thanks for being so helpful in mathematics. If you are getting quality help, make sure you spread the word about OpenStudy.

This is the testimonial you wrote.
You haven't written a testimonial for Owlfred.