Python Using `!=`, `or` And `while`
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: # som
Solution 1:
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:
Solution 2:
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.
Solution 3:
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
Post a Comment for "Python Using `!=`, `or` And `while`"