Brian Harris
Brian Harris

Reputation: 2795

why does this python program print True

x=True
def stupid():
    x=False
stupid()
print x

Upvotes: 7

Views: 491

Answers (8)

newacct
newacct

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

Sev
Sev

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"

  • 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.

Upvotes: 6

too much php
too much php

Reputation: 90978

  • 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().

Upvotes: 2

Stobor
Stobor

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

Greg Hewgill
Greg Hewgill

Reputation: 992717

To answer your next question, use global:

x=True
def stupid():
    global x
    x=False
stupid()
print x

Upvotes: 10

lilbyrdie
lilbyrdie

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

Harold L
Harold L

Reputation: 5254

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

Upvotes: 2

Jonathan Graehl
Jonathan Graehl

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

Related Questions