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

时间:2010-01-27 11:27:33

标签: python logic

我在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

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

由于

6 个答案:

答案 0 :(得分:18)

and更改为or s。

答案 1 :(得分:2)

while not condition1 or not condition2 or val == -1:

但是你原来使用if一段时间内没有错。

答案 2 :(得分:1)

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

另请注意,在Python中,not condition优先于condition == False;同样,condition优先于condition == True

答案 3 :(得分: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

答案 4 :(得分:-1)

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

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

    if something1==10:
        condition1 = True

    if something2==20:
        condition2 = True

答案 5 :(得分:-2)

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

while 1:
  if condition1 and condition2:
      break
  ...
  ...
  if condition3: break
  ...
  ...