pythonoperatorsnot-operator

Python operator != isn't working as expected


Does anyone know why this sample is not working? I have not used Python in years and wanted to test NOT operators. As far as I can remember this should work, I have checked online and it appears to be the correct format. Am I missing something?

Essentially it is just asking for an input of 1, 2 or 3. If the user enters those it will break out the loop. If they do not enter either 1, 2 or 3 it will print to screen and loop again. Currently it is only printing "Invalid input!" then looping not breaking.

while True:
    x = input("1, 2, or 3?\n")
    if x != 1 or x != 2 or x != 3:
        print("Invalid input!")
    else:
        break

I am using Python 3.6.4.


Solution

  • Well, this will be always true. if I type 1, it'll fail the first condition, but it'll pass the other two: x != 2 or x != 3. Any other number different than 1, 2 or 3 will also be true for all the conditions. There's no problem with the comparison operator.

    I think you want to do something like:

    x = int(input("1, 2, or 3?\n"))
    if x not in [1, 2, 3]:
        print("Invalid input!")
    

    The conversion of x to int is also important. Otherwise, the comparison of x with the numbers will be always false.