26

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

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
mikip
  • 1,677
  • 6
  • 25
  • 35
  • Can you clarify what you mean by "the code above does not work". What happens when you have the condition in the while statement? – Tendayi Mawushe Jan 27 '10 at 11:36
  • Hi The first bit of code breaks out if any of the conditions are met, I want to break out when all the conditions are met Thanks – mikip Jan 27 '10 at 11:45

6 Answers6

22

Change the ands to ors.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • @SilentGhost: The condition given in the first blurb (which *maintains* the loop) is almost the negation of the condition given in the second blurb (which *breaks* the loop), except that it uses the wrong logical operator. – Ignacio Vazquez-Abrams Jan 27 '10 at 11:44
3
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.

1

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.

tzot
  • 92,761
  • 29
  • 141
  • 204
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
MIIK7
  • 1
  • 1
-1

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
Tendayi Mawushe
  • 25,562
  • 6
  • 51
  • 57
-2

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
  ...
  ...
ghostdog74
  • 327,991
  • 56
  • 259
  • 343