Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

or condition in while loop python

Does or condition work in a while loop in python? I can't seem to make it work. This is the sample of how my code works.

newslot = 3
moved = False

while newslot > 0 or moved != True:
    enabled = query something on the database where slot = newslot
    if enabled:
        print 'do something here'
        moved = True
    else:
        newslot-=1
        print 'slot disabled'

So when the newslot gets to value of zero it still proceeds to go inside the while loop. I seem to be missing something here.


1 Answers

or is working as should be expected. A while loop will continue until its condition is false. If its condition is two separate conditions connected with an or, it will only be false when the two conditions are both false.

Your loop will continue repeating until moved is false and newslot is <= 0. I'm guessing you actually want to use and in this case, as you want the loop to stop once either condition is met.

like image 93
StephenTG Avatar answered Sep 28 '26 07:09

StephenTG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!