Search code examples
pythoncomparisonoperator-keywordcontrol-flow

Not equals comparison on cased letters


I have this:

salir = ""
while  salir != "s" or salir != "S":
       print("no has salido")
       salir = input("Digit s to exit or enter to continue)
print("saliste")

but the operator != doesnt work, but if I put this:

salir = ""
while  not (salir == "s" or salir == "S"):
       print("no has salido")
       salir = input("Digit s to exit or enter to continue")
print("saliste")

the code works normal, the problem is the comparison operator != because if I change that by " not == " this works. Can anybody explain the problem?


Solution

  • The expression you are evaluating always returns True

    salir != "s" or salir != "S" == True  # always
    

    If the user inputs 's', then salir != "S"

    If the user inputs 'S', then salir != "s"

    If you want to split the two cases (instead of calling the lower() method) you can use the loop

    while  salir != "s" and salir != "S":
        # Do stuff
    

    By DeMorgan's law this is equivalent to

    while  not (salir == "s" or salir == "S"):
        # Do stuff