1

I'm trying something realy easy, but it's not working.

I want to change the boolean value of x, from True to False, but even though I'm returning x with it new value, when I check, it seems that the value never changed.

x = True

def example():
    x = False
    return x

example()
print(x)

It prints that x is True, and the boolean value of x doesnt change, I think that the problem is the use of the def and return statement, but, clearly I dont know what I'm doing wrong.

Thanks in advance! :D

David
  • 35
  • 3
  • 1
    Does this answer your question? [Using global variables in a function](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) – Countour-Integral Jan 22 '21 at 21:30

3 Answers3

2

Do one of the followings :

This (recommended) :

x = True

def example(x):
    return not x #it will flip the value. if you need it to be always false, change it

x = example(x)
print(x)

Or This

x = True

def example():
    global x
    x = not x

example()
print(x)
Behzad Shayegh
  • 323
  • 1
  • 10
1

This is thanks to the intricacies of python variable creation, and what you are trying to do is change what python sees as a global variable. This is answered in much more depth in this post but in short, adding the global keyword in functions specifying the variables will solve your problem.

x = True

def example():
    global x
    x = False
    return x

example()
print(x)
jacobeng3l
  • 51
  • 2
0

To change the variable in the outer scope, you need to explicitly assign to it, like so:

x = True

def example():
    return False

x = example()
print(x)
# False

In the code you posted, variable x in the outer scope is implicitly hidden by variable x in the inner scope of function example. When the function is done executing, the inner scope x goes out of existence, leaving just the outer scope variable x, which retains the same value as before.

SEE ALSO:
Python 2.x gotchas and landmines - Stack Overflow
Python Scope & the LEGB Rule: Resolving Names in Your Code – Real Python: Using the LEGB Rule for Python Scope

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47