如何使用!=在if / else子句中正确签名?

问题描述 投票:2回答:3

问题:如果用户输入单词!='encrypt'或'decrypt',我试图再次调用ask_user(),但输入IS正确时会出现相同的错误消息。

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:   ")

似乎在同一行上使用多个!=语句并不像我想象的那样工作:

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

我该如何更改代码来解决此问题?

python comparison equality boolean-logic
3个回答
2
投票

你的问题是你使用or而不是and。如果您考虑如何解释代码:

让我们说,mode="encrypt"。一步步:

mode != 'encrypt'评估为false。到目前为止都很好。

然而,mode != 'decrypt'true进行了评估。这是个问题。

发送给if的最终表达式为:false or true。最后,这将评估为true,导致输入if块。

将其更改为and意味着必须检查两个无效模式true以输入块。


2
投票

n != 2 or n != 3永远是真的。如果n2那么它不是3。所有其他值不是2

你打算n != 2 and n != 3


0
投票

你需要使用and,而不是or。因为n将永远不会等于3和4,所以包含ifor声明将始终解析为True

© www.soinside.com 2019 - 2024. All rights reserved.