Reputation: 2795
x=True
def stupid():
x=False
stupid()
print x
Upvotes: 7
Views: 491
Reputation: 122429
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
Upvotes: 5
Reputation: 15699
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"
Upvotes: 6
Reputation: 90978
x
inside stupid()
, Python creates a new x
inside stupid()
.x
inside stupid()
, Python would in fact use the global x
, which is what you wanted.x
, add global x
as the first line inside stupid()
.Upvotes: 2
Reputation: 45122
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
Upvotes: 3
Reputation: 992717
To answer your next question, use global
:
x=True
def stupid():
global x
x=False
stupid()
print x
Upvotes: 10
Reputation: 1907
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.
Upvotes: 2
Reputation: 5254
The x in the function stupid() is a local variable, so you really have 2 variables named x.
Upvotes: 2
Reputation: 9301
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
Upvotes: 18