x=True
def stupid():
x=False
stupid()
print x
views:
330answers:
8You don't need to declare a function-local variable in Python. The "x=False" is referring to an x local to stupid(). If you really want to modify the global x inside stupid:
def stupid():
global x
x=False
The x in the function stupid() is a local variable, so you really have 2 variables named x.
Because x's scope is local to the function stupid(). once you call the function, and it ends, you're out of it's scope, and you print the value of "x" that's defined outside of the function stupid() -- and, the x that's defined inside of function stupid() doesn't exist on the stack anymore (once that function ends)
edit after your comment:
the outer x is referenced when you printed it, just like you did.
the inner x can only be referenced whilst your inside the function stupid(). so you can print inside of that function so that you see what value the x inside of it holds.
About "global"
- it works & answers the question, apparently
- not a good idea to use all that often
- causes readability and scalability issues (and potentially more)
- depending on your project, you may want to reconsider using a global variable defined inside of a local function.
Add "global x" before x=False in the function and it will print True. Otherwise, it's there are two "x"'s, each in a different scope.
To answer your next question, use global:
x=True
def stupid():
global x
x=False
stupid()
print x
If you want to access the global variable x from a method in python, you need to do so explicitly:
x=True
def stupid():
global x
x=False
stupid()
print x
- Because you're making an assignment to
xinsidestupid(), Python creates a newxinsidestupid(). - If you were only reading from
xinsidestupid(), Python would in fact use the globalx, which is what you wanted. - To force Python to use the global
x, addglobal xas the first line insidestupid().
If that code is all inside a function though, global is not going to work, because then x would not be a global variable. In Python 3.x, they introduced the nonlocal keyword, which would make the code work regardless of whether it is at the top level or inside a function:
x=True
def stupid():
nonlocal x
x=False
stupid()
print x