Python 如何使用多个条件执行while循环
我在python中有一个while循环Python 如何使用多个条件执行while循环,python,logic,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: co
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
好的,这是最好的方法吗
谢谢将
和
s更改为或
s。像最初那样使用无限循环。它是最干净的,你可以根据自己的意愿结合多种条件
while 1:
if condition1 and condition2:
break
...
...
if condition3: break
...
...
但是,在一段时间内使用if的原作没有什么错。我不确定它会读得更好,但你可以做以下几点:
while any((not condition1, not condition2, val == -1)):
val,something1,something2 = getstuff()
if something1==10:
condition1 = True
if something2==20:
condition2 = True
您是否注意到,在您发布的代码中,
condition2
从未设置为False
?这样,就永远不会执行循环体
另外,请注意,在Python中,
not condition
优先于condition==False
;同样地,condition
比condition==True更可取
您能澄清一下“上面的代码不起作用”是什么意思吗。当while语句中有条件时会发生什么情况?嗨,如果满足任何条件,代码的第一位就会中断,我想在满足所有条件时中断Thanks@SilentGhost:第一个模糊中给出的条件(保持循环)几乎与第二个模糊中给出的条件相反(这会中断循环),但它使用了错误的逻辑运算符。
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
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