简体   繁体   中英

While loop with multiple conditions until one condition is met, in python

ORIGINAL:

I'm trying to have a while loop that checks two conditions and stops if one condition is met. My exact needs are something that goes like this

while integer1 AND integer2 > 0:
  # perform calculation and print results at each instance of the loop

REPHRASING: I need to make a loop that runs until one of two numbers becomes zero, and each of those numbers will change during each iteration of the loop.

Sorry if my original phrasing was confusing, hope this makes more sense.

I suppose one could use:

while all([x > 0 for x in a,b,c]):
    be_happy()

... in other words you could use a list comprehension expression and test all() on that.

For only two variables this would be a bit obtuse. I'd just use:

while a > 0 and b > 0:

... but for more than two I'd suggest all. You can use a list comprehension as shown or you could use a generator expression thus:

while all((x>0 for x in (a,b,c))):

... as shown it seems to be necessary to enclose the tuple in (parentheses) in this case whereas it wasn't necessary in my test of my earlier example.

Personally I think the list comprehension is marginally more readable. But that may be more subjective than anything.

Also note that you can use the any() built-in for the rather obvious alternatively semantics.

The integers except 0 assumes as True by python when you use them as condition so actually you have , and note that and (not AND) operand works works for chain 2 condition!:

while True and integer2 > 0: 

instead you need :

while integer1 > 0 and integer2 > 0:

But if you want to make a loop that runs until one of two numbers becomes zero you need and and you need to decrees your integers inside the loop!

while integer1 > 0 and integer2 > 0:
   #do stuff
   #for example integer1 -=1
   #integer2 -=1  

The above answers look like they'll solve your problem, but to explain why your code isn't working, both sides of an AND expression are treated as separate conditions and will become either true or false. You're not saying "while both integer1 and integer2 are greater than zero", you saying, "while integer1 is not false and while integer2 is greater than zero". Note that those are two separate conditions.

On the right, when integer2 is greater than zero,

integer2 > 0

will turn into True for the condition. On the left, however,

integer1

is the whole condition, and it will turn into true when it is not zero. See Python Truth Value Testing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM