简体   繁体   English

Python变量不会改变吗?

[英]Python variable won't change?

I'm making a game in python, and I have some code set up as such: 我正在用python做游戏,并且我设置了一些代码,例如:

istouching = False
death = True

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

while death is False:
    print death
    game logic

I know the game logic is working, because "Is touching" prints, but then when I print out the value of death, it remains false, any help? 我知道游戏逻辑在起作用,因为“正在触摸”打印出来了,但是当我打印出死亡的价值时,它仍然是错误的,有什么帮助吗?

use global to change global variables inside a function, otherwise death=True inside checkdead() will actually define a new local variable. 使用global来更改函数内部的全局变量,否则, checkdead()内部的death=True实际上将定义一个新的局部变量。

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

Make checkdead return a value: 使checkdead返回一个值:

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

death = checkdead()

You could also use global , as @AshwiniChaudhar shows, but I think it is preferable to write functions that return values instead of functions that modify globals, since such functions can be unit-tested more easily, and it makes explicit what external variables are changed. 您也可以使用global ,如@AshwiniChaudhar所示,但我认为最好编写返回值的函数,而不是修改全局变量的函数,因为这样的函数可以更容易地进行单元测试,并且可以明确指出要更改的外部变量。

PS. PS。 if istouching = True should have resulted in a SyntaxError since you can not make a variable assignment inside a conditional expression. if istouching = True应该导致SyntaxError,因为您不能在条件表达式中进行变量赋值。

Instead, use 相反,使用

if istouching:

That's scope-related. 这与范围有关。

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