如何执行具有多个条件的 while 循环
我在 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
代码可以正常工作,这是最好的方法吗?
谢谢
I have a while loop in python
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
'
'
I want to break out of the loop when all these conditions are true, the code above does not work
I originally had
while True:
if condition1==True and condition2==True and val!=-1:
break
which works ok, is this the best way to do this?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
将
and
更改为or
。Change the
and
s toor
s.但是你原来在一段时间内使用 if 的做法没有任何问题 True 。
But there was nothing wrong with your original of using an if inside of a while True.
您是否注意到在您发布的代码中,
condition2
从未设置为False
?这样,你的循环体就永远不会被执行。另请注意,在 Python 中,
not condition
优先于condition == False
;同样,condition
优先于condition == True
。Have you noticed that in the code you posted,
condition2
is never set toFalse
? This way, your loop body is never executed.Also, note that in Python,
not condition
is preferred tocondition == False
; likewise,condition
is preferred tocondition == True
.我不确定它会读起来更好,但你可以执行以下操作:
I am not sure it would read better but you could do the following:
使用像您最初所做的那样的无限循环。它是最干净的,您可以根据需要合并许多条件
use an infinity loop like what you have originally done. Its cleanest and you can incorporate many conditions as you wish