Python变量不会改变吗? [英] Python variable won't change?
问题描述
我正在用python制作游戏,并且我已经设置了一些代码:
I'm making a game in python, and I have some code set up as such:
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?
推荐答案
使checkdead
返回值:
def checkdead():
if istouching:
print "Is touching"
return True
death = checkdead()
您也可以使用global
,如@AshwiniChaudhar所示,但我认为编写返回值的函数而不是修改全局变量的函数是可取的,因为这样的函数可以更容易地进行单元测试,并且可以显式地进行测试.哪些外部变量发生了变化.
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.
PS. if istouching = True
应该导致了SyntaxError,因为您不能在条件表达式中进行变量赋值.
PS. if istouching = True
should have resulted in a SyntaxError since you can not make a variable assignment inside a conditional expression.
相反,使用
if istouching:
这篇关于Python变量不会改变吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!