Jump to content
  • Advertisement
Sign in to follow this  

Python: The variable's value changes back to default.

This topic is 4126 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi! Short question: I have a vriable defined on module level, in a function at the same level i have an if-statement that reads from that variable. When done I want the variable's value to change, so I set the new value and it works inside that function. But the next time the loop runs my function, the value of the variable is the default again. My code looks somewhat like this:
[source lange="python"]var = "1"

def lookIntoVar():
    if var == "1":
        print var
        var = "2"
        print var
        var = "1"
Why is Python behaving this way, and how do I solve my problem?

Share this post

Link to post
Share on other sites
Python doesn't let you access global variables in functions by default. Your assignment to var actually creates a function-local variable called var. You have to declare it as global in the function, as follows:

def bar():
global foo
# now you can use the global foo

Of course, global variables are usually not a good idea anyway.

EDIT: Your example should (and does) throw an exception, because you try to read from a local variable before assigning it a value.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!