x=True
def stupid():
x=False
stupid()
print x
8 Answers
You 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
1 Comment
print x inside the function it would use the global x. It's only assignment that creates the new local variable.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.
Comments
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
Comments
- 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().
x=Truewithx = [1], and replacex=Falsewithx[0] = 2and run your code again..