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
andchoice
is not 2
either. Example -
whilechoice!=1andchoice!=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
whilechoice!=1orchoice!=2:
the problem is
whilechoice!=1 or 2:
is evaluated left to right so pretend choice = 3
while3 != 1or2: = > while (3 != 1) or2: ==> while (False) or2: =>> 2is always true so it doesnt work
Post a Comment for "Python Using `!=`, `or` And `while`"