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

Started by
1 comment, last by Zyndrof 16 years, 8 months ago
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?
Advertisement
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.
Aha, I see. Thank you :)

This topic is closed to new replies.

Advertisement