如何在whileloop中添加多个条件

2024-04-26 21:24:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个基于文本的游戏,其中包含多个你必须保持的统计数据,例如耐力、健康等。如果这些数据低于0,我会遇到问题。我知道一段时间的循环是可行的,我可以做到:

life = 1
while(life > 0):
    print("You are alive!")
    print("Oh no! You got shot! -1 Life")
    life-1
print("You are dead! Game Over!")

但我不知道如何在耐力、饥饿、力量等多种情况下做到这一点


Tags: 数据no文本you游戏are统计数据oh
3条回答

可以使用^{}将它们组合到一个测试中:

while min(life, health, stamina) > 0:

始终可以使用andor。例如:

while (life > 0) and (health > 0) and (stamina > 0):

因为在Python中0的计算结果是False,所以可以使用^{}

while all((life, stamina, hunger, strength)):

这将测试所有名称是否都不等于零。你知道吗

但是,如果您需要测试所有名称是否都大于零(也就是说,它们可能变成负数),您可以添加generator expression

while all(x > 0 for x in (life, stamina, hunger, strength)):

相关问题 更多 >