Return 应用布尔值时无法正常工作

Return not functioning when applaying booleans

我正在尝试一些非常简单的方法,但它不起作用。

我想将 x 的布尔值从 True 更改为 False,但即使我 returning x 的新值,当我检查时,该值似乎从未改变。

x = True

def example():
    x = False
    return x

example()
print(x)

它打印出 x 为 True,并且 x 的布尔值没有改变,我认为问题出在 def 和 return 语句的使用上,但是,显然我不知道我在做什么做错了。

提前致谢! :D

执行以下操作之一:

这个(推荐):

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)

或者这个

x = True

def example():
    global x
    x = not x

example()
print(x)

这要归功于 python 变量创建的复杂性,而您要做的是更改 python 视为 global 变量的内容。这在 this post 中得到了更深入的回答,但简而言之,在指定变量的函数中添加 global 关键字将解决您的问题。

x = True

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

example()
print(x)

要改变外部范围内的变量,你需要显式地赋值给它,像这样:

x = True

def example():
    return False

x = example()
print(x)
# False

在您发布的代码中,外部作用域中的变量 x 被函数 example 内部作用域中的变量 x 隐式隐藏。函数执行完毕后,内部作用域 x 不复存在,只留下外部作用域变量 x,其值与之前相同。

另请参见:
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