tags:

views:

330

answers:

8
x=True
def stupid():
    x=False
stupid()
print x
+17  A: 

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
wrang-wrang
Note that if you did the `print x` inside the function it would use the global `x`. It's only *assignment* that creates the new local variable.
quark
+2  A: 

The x in the function stupid() is a local variable, so you really have 2 variables named x.

Harold L
+6  A: 

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.
Sev
+2  A: 

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.

lilbyrdie
+10  A: 

To answer your next question, use global:

x=True
def stupid():
    global x
    x=False
stupid()
print x
Greg Hewgill
haha nice pre-emptive answering.
Triptych
+3  A: 

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
Stobor
Weird hiccup there. :(
Stobor
+2  A: 
  • Because you're making an assignment to x inside stupid(), Python creates a new x inside stupid().
  • If you were only reading from x inside stupid(), Python would in fact use the global x, which is what you wanted.
  • To force Python to use the global x, add global x as the first line inside stupid().
too much php
+5  A: 

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
newacct