3

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.

6
  • 2
    What isn't working? Also, what is the value of slot? Commented Mar 14, 2016 at 17:28
  • What are the values of slot and enabled? Commented Mar 14, 2016 at 17:29
  • 1
    or is working but if slot is enabled is True then, your loop never ends since newslot > 0 remains True Commented Mar 14, 2016 at 17:30
  • 1
    @test NO. it will continue when either one is True. You need and instead of or Commented Mar 14, 2016 at 17:33
  • 1
    or means when at least one statement is True the while loop will continue Commented Mar 14, 2016 at 17:33

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

well that was confusing, i thought when I used or, i didnt have to satisfy both conditions, anyway thanks for the help, i will use and instead.
@test A while loop will continue as long as its condition is true. If you have two conditions connected with an or, the loop will only end once both are false, as if one is true then the entire or is true.
I see, thats stupid of me. I thought the other way around. Thanks alot for clarifying. @StephenTG
@test No problem, happy to help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.