如何在具有多个条件的循环中执行

问题描述 投票:17回答:6

我在python中有一个while循环

condition1=False
condition1=False
val = -1

while condition1==False and condition2==False and val==-1:
    val,something1,something2 = getstuff()

    if something1==10:
        condition1 = True

    if something2==20:
        condition2 = True

'
'

当所有这些条件都成立时,我想要摆脱循环,上面的代码不起作用

我原本有

while True:
      if condition1==True and condition2==True and val!=-1:
         break

哪个工作正常,这是最好的方法吗?

谢谢

python logic
6个回答
18
投票

ands更改为ors。


2
投票
while not condition1 or not condition2 or val == -1:

但是你的原始使用if一段时间内没有任何问题。


1
投票

您是否注意到在您发布的代码中,condition2从未设置为False?这样,您的循环体永远不会被执行。

另外,请注意,在Python中,not conditioncondition == False更受欢迎;同样,condition优于condition == True


0
投票
condition1 = False
condition2 = False
val = -1
#here is the function getstuff is not defined, i hope you define it before
#calling it into while loop code

while condition1 and condition2 is False and val == -1:
#as you can see above , we can write that in a simplified syntax.
    val,something1,something2 = getstuff()

    if something1 == 10:
        condition1 = True

    elif something2 == 20:
# here you don't have to use "if" over and over, if have to then write "elif" instead    
    condition2 = True
# ihope it can be helpfull

-1
投票

我不确定它会读得更好,但你可以做到以下几点:

while any((not condition1, not condition2, val == -1)):
    val,something1,something2 = getstuff()

    if something1==10:
        condition1 = True

    if something2==20:
        condition2 = True

-2
投票

像你原来做的那样使用无限循环。它最干净,你可以根据自己的意愿纳入许多条件

while 1:
  if condition1 and condition2:
      break
  ...
  ...
  if condition3: break
  ...
  ...
© www.soinside.com 2019 - 2024. All rights reserved.