繁体   English   中英

Python变量不会改变吗?

[英]Python variable won't change?

我正在用python做游戏,并且我设置了一些代码,例如:

istouching = False
death = True

def checkdead():
    if istouching:
        print "Is touching"     
        death = True

while death is False:
    print death
    game logic

我知道游戏逻辑在起作用,因为“正在触摸”打印出来了,但是当我打印出死亡的价值时,它仍然是错误的,有什么帮助吗?

使用global来更改函数内部的全局变量,否则, checkdead()内部的death=True实际上将定义一个新的局部变量。

def checkdead():
    global death
    if istouching == True:      #use == here for comparison
        print "Is touching"     
        death = True

使checkdead返回一个值:

def checkdead():
    if istouching:
        print "Is touching"     
        return True

death = checkdead()

您也可以使用global ,如@AshwiniChaudhar所示,但我认为最好编写返回值的函数,而不是修改全局变量的函数,因为这样的函数可以更容易地进行单元测试,并且可以明确指出要更改的外部变量。

PS。 if istouching = True应该导致SyntaxError,因为您不能在条件表达式中进行变量赋值。

相反,使用

if istouching:

这与范围有关。

death = False        
def f():
    death = True      # Here python doesn't now death, so it creates a new, different variable
f()
print(death)          # False

death = False       
def f():
    global death
    death = True
f()
print(death)      # True

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM