2017-06-15 58 views
1
done = False 
player_health = 2 
def lost_game(done): 
    if player_health <= 0: 
     done = True 
     print ('You died') 
     return done 
while not done: 
    print 'okay' 
    player_health -= 1 

我想不通爲什麼done永遠不會設置爲True,從而結束了while循環。我的函數的返回值是不是全局,不會結束「而」循環

+4

你在哪裏叫'lost_game()'?它返回值,您應該將其分配給循環中的變量。 – Barmar

+1

爲什麼'lost_game()'將'done'作爲參數?它從不使用它。 – Barmar

+0

是啊,我的壞! Prune在下面糾正了我。我沒有意識到我不需要「完成」作爲參數。對於不調用該函數,我只是忘了複製並粘貼它。感謝您的幫助! <3 –

回答

1

它未設置爲True,因爲它是局部變量。 如果你想影響與功能分配全局變量,你必須聲明它這樣的:

def lost_game(): 
    global done 
    if player_health <= 0: 
     done = True 

另外請注意,你從來沒有叫lost_game功能。我不確定你期望的控制流量。它看起來像你可能想要一個簡單的循環:

done = False 
player_health = 2 
while not done: 
    if player_health <= 0: 
     done = True 
     print ('You died') 

print 'okay' 
player_health -= 1 

......或許它只是你沒有調用該函數並獲取返回值:

done = False 
player_health = 2 

def lost_game(): 
    done = False 
    if player_health <= 0: 
     done = True 
     print ('You died') 
     return done 

while not lost_game(): 
    print 'okay' 
    player_health -= 1 
+0

對不起!這是我的第一年編碼,所以我有點過分了。第一個爲我做了詭計。我忘了複製並粘貼完整的代碼(這就是爲什麼我沒有調用函數)。 MB!非常感謝你的幫助:D –

+0

太好了。我看到你已經討論過其他地方的選票了(我點了幾個)。 – Prune

1

你永遠呼喚lost_game()lost_game()返回值作爲一個結果,所以你應該使用而不是變量:

player_health = 2 

def lost_game(): 
    if player_health <= 0: 
     print ('You died') 
     return True 
    else: 
     return False 

while not lost_game(): 
    print 'okay' 
    player_health -= 1 

lost_game()並不需要的參數。

+0

謝謝:D!我沒有rep up to upvote,但只知道我做到了!你和Prune幫了我很多。謝啦! –

+0

接受最有用的答案,你不需要upvote。 – Barmar

1

只需更新while循環:

while not done: 
    print 'okay' 
    player_health -= 1 
    done = lost_game(done) 

順便說一下有沒有需要通過你的lost_game函數調用來完成。