Why is this python program printing True

x=True def stupid(): x=False stupid() print x 
+7
python
source share
8 answers

You do not need to declare a locally variable function in Python. "X = False" refers to x local to dupid (). If you really want to change global x inside is stupid:

 def stupid(): global x x=False 
+18
source share

To answer the following question, use global :

 x=True def stupid(): global x x=False stupid() print x 
+10
source share

Since the region x is local to the stupid () function. as soon as you call the function and it ends, you go out of scope and you print the value "x" which is defined outside the dupid () function - and x defined inside the stupid () function no longer exists on the stack (as soon as this function ends)

edit after your comment:

outer x refers when you printed it, just like you did.

inner x can only be specified if you are stupid () inside the function. so you can print inside this function so that you can see what value x has inside it.

About the "global"

  • it works and answers the question, apparently
  • It is not recommended to use all that often
  • causes readability and scalability issues (and possibly more)
  • depending on your project, you might want to reconsider using a global variable defined inside a local function.
+6
source share

If this code is all inside the function, but global will not work, because then x will not be a global variable. In Python 3.x, they introduced the nonlocal keyword, which will 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 
+5
source share

If you want to access the global variable x from a method in python, you need to do this explicitly:

 x=True def stupid(): global x x=False stupid() print x 
+3
source share

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

+2
source share

Add "global x" to x = False in the function and it will print True. Otherwise, these are two "x", each in a different area.

+2
source share
  • Since you are assigning x inside stupid() , Python creates a new x inside stupid() .
  • If you read only x inside stupid() , Python would actually use the global x that you wanted.
  • To force Python to use global x , add global x to the first line inside stupid() .
+2
source share

All Articles