Search code examples
pythoncomparisonequalityboolean-logic

How to use != sign correctly in if/else clause?


Problem: I'm trying to invoke ask_user() again if the user inputs words != 'encrypt' or 'decrypt', but the same error message appears when the input IS correct.

def ask_user():
    while True:
        mode = input("Would you like to encrypt or decrypt:   ")
        if mode != 'encrypt' or mode != 'decrypt':          
            print("Please retry; you must type lowercase. \n")
            ask_user()

        else:
            message = input("Enter your message:   ")

It seems that using more than one != statements on same line doesn't work as I'd imagined:

# test to support above observ.
for n in range(4):
    if n != 2 or n != 3:
        print('me')
    else:
        print(n)

How should I change the code to fix this problem?


Solution

  • Your problem is that you are using or instead of and. If you think about how the code is interpreted:

    Let's say that mode="encrypt". Step by step:

    mode != 'encrypt' evaluates to false. All good so far.

    mode != 'decrypt', however, evaluates to true. This is a problem.

    The final expression sent to the if will be: false or true. This, finally, evaluates to true, causing the if block to be entered.

    Changing it to and means that both of invalid modes will have to be checked true for the block to be entered.