while 循环多个条件,直到满足一个条件,in python

While loop with multiple conditions until one condition is met, in python

原创:

我正在尝试使用一个 while 循环来检查两个条件并在满足一个条件时停止。 我的确切需求是这样的

while integer1 AND integer2 > 0:
  # perform calculation and print results at each instance of the loop

重述: 我需要创建一个循环,一直运行到两个数字之一变为零,并且每个数字都会在循环的每次迭代中发生变化。

抱歉,如果我原来的措辞令人困惑,希望这更有意义。

当您将它们用作条件时,True 将除 0 以外的整数假设为 True,因此实际上您有,并注意 and(不是 AND)操作数适用于链2条件!:

while True and integer2 > 0: 

相反,您需要:

while integer1 > 0 and integer2 > 0:

但是如果你想创建一个循环直到两个数字之一变为零,你需要并且你需要在循环内计算你的整数!

while integer1 > 0 and integer2 > 0:
   #do stuff
   #for example integer1 -=1
   #integer2 -=1  

我想可以使用:

while all([x > 0 for x in a,b,c]):
    be_happy()

...换句话说,您可以使用列表理解表达式并对其进行测试 all()

对于只有两个变量,这会有点迟钝。我只是使用:

while a > 0 and b > 0:

...但如果超过两个,我会建议全部。您可以使用所示的列表理解,也可以使用生成器表达式:

while all((x>0 for x in (a,b,c))):

...如图所示,在这种情况下似乎有必要将元组括在(括号)中,而在我对之前示例的测试中则没有必要。

我个人认为列表推导式的可读性稍微好一些。但这可能比任何事情都更主观。

另请注意,您可以使用内置的 any() 来获得相当明显的替代语义。

以上答案看起来可以解决您的问题,但为了解释您的代码为何不起作用,AND 表达式的两边都被视为单独的条件,并且会变为真或假。你不是说 "while both integer1 and integer2 are greater than zero",你说的是 "while integer1 is not false and while integer2 is greater than zero"。请注意,这是两个不同的条件。

右边,当integer2大于零时,

integer2 > 0

条件将变为 True。然而在左边,

integer1

是整个条件,不为零则变为真。参见 Python Truth Value Testing