簡體   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