Sign in to follow this  
Zyndrof

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

Recommended Posts

Zyndrof    163
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"
    else:
        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
Sharlin    864
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:

foo=42;
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this