[source lange="python"]var = "1"
def lookIntoVar():
if var == "1":
print var
var = "2"
else:
print var
var = "1"
Python: The variable's value changes back to default.
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:
Why is Python behaving this way, and how do I solve my problem?
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:
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.
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement