0

For example, I want to run the loop when choice isn't neither1 nor 2. So my code is like this:

choice = int(input('Enter a number: '))

while choice != 1 or choice != 2:
    # some code here

Now here is my question, whatever choice is 1, 2, or other, this loop will still run because choice can't be 1 and 2 at once. And I don't know why does this also don't work:

while choice != 1 or 2:
    # some code here

I'm sorry if this is a duplicate.

Remi Guan
  • 21,506
  • 17
  • 64
  • 87

3 Answers3

2

The issue is that you are using or , you have to use and since you want to check that choice is not 1 and choice is not 2 either. Example -

while choice != 1 and choice != 2:
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
1

Every number is either not 1 or not 2. What you want is for it to be not 1 and not 2. So do while choice != 1 and choice != 2.

You can also do while choice not in (1, 2), which is more easily extensible to a larger set of values to check against.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
1
while choice not in [1,2]:

or

while choice != 1 or choice != 2:

the problem is

while choice != 1 or 2:

is evaluated left to right so pretend choice = 3

while 3 != 1 or 2: = > while (3 != 1) or 2: ==> while (False) or 2: =>> 2 is always true so it doesnt work
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179