简体   繁体   English

如何在while循环中添加多个条件

[英]How to add multiple conditions in a while-loop

I'm creating a text based game with multiple stats you have to keep up, such as stamina, health, etc. and I am having trouble with what happens if they go below 0 . 我正在创建一个具有多个统计数据的基于文本的游戏,您必须保持这些统计数据,例如耐力,健康状况等,但是当它们低于0时会发生什么情况,我遇到了麻烦。 I know a while-loop would work I could do: 我知道可以执行while循环:

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!")

But I don't know how to do that with multiple conditions such as stamina, hunger, strength etc. 但是我不知道如何在多个条件下做到这一点,例如耐力,饥饿,力量等。

您可以使用min将它们合并为一个测试:

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

Since 0 evaluates to False in Python, you can use all : 由于在Python中0值为False ,因此可以使用all

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

This will test if all of the names are not equal to zero. 这将测试所有名称是否不等于零。

If however you need to test if all of the names are greater than zero (meaning, they could become negative), you can add in a generator expression : 但是,如果您需要测试所有名称是否都大于零(意味着它们可能变为负数),则可以添加一个生成器表达式

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

You can always use and and or . 您可以始终使用andor For example: 例如:

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

You could put if statements into the while loop that check those stats at the start of each iteration. 您可以将if语句放入while循环中,以在每次迭代开始时检查这些状态。 That way you can handle each event individually. 这样,您可以单独处理每个事件。

life = 1
while(life > 0):
    if stamina < 1:
        print "out of stamina"
        break
    if hunger < 1:
        print "You died of hunger"
        break
    print("You are alive!")
    print("Oh no! You got shot! -1 Life")
    life-1
print("You are dead! Game Over!")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM