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循环。
答案 0 :(得分: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
答案 1 :(得分: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()
不需要参数。
答案 2 :(得分:1)
只需更新你的while循环:
while not done:
print 'okay'
player_health -= 1
done = lost_game(done)
顺便说一下,你的lost_game函数调用不需要传递。