tags:

views:

497

answers:

5

Hi

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

+3  A: 

Change the ands to ors.

Ignacio Vazquez-Abrams
Hi thanks , but why does this make it work
mikip
http://en.wikipedia.org/wiki/De_Morgan%27s_laws
Ignacio Vazquez-Abrams
@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
A: 

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
+1  A: 
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.

Paul Hankin
A: 

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
A: 

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.

ΤΖΩΤΖΙΟΥ