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 condit开发者_StackOverflowion1==True and condition2==True and val!=-1:
break
which works ok, is this the best way to do this?
Thanks
Change the and
s to or
s.
while not condition1 or not condition2 or val == -1:
But there was nothing wrong with your original of using an if inside of a while True.
Have you noticed that in the code you posted, condition2
is never set to False
? This way, your loop body is never executed.
Also, note that in Python, not condition
is preferred to condition == False
; likewise, condition
is preferred to condition == True
.
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
I am not sure it would read better but you could do the following:
while any((not condition1, not condition2, val == -1)):
val,something1,something2 = getstuff()
if something1==10:
condition1 = True
if something2==20:
condition2 = True
use an infinity loop like what you have originally done. Its cleanest and you can incorporate many conditions as you wish
while 1:
if condition1 and condition2:
break
...
...
if condition3: break
...
...
精彩评论