This question already has answers here:
How to test multiple variables against a value?

(25个答案)



Elif and if not working or me not understanding [duplicate]

(3个答案)


7年前关闭。




我想检查一个变量是否具有多个值之一。我对为什么or在这种情况下不起作用感到困惑。我正在按照给出if (a or b):示例的教程进行操作,但是当我尝试执行此操作时,它只会根据第一个值检查变量。我的支票怎么了?
name = raw_input('Please type in your name:')

if len(name) < 5:
    print "Your name has fewer than 5 characters"
elif len(name) == 5:
    print "Your name has exactly 5 characters"
    if name == ("Jesse" or "jesse"):
        print "Hey Jesse!"
else:
    print "Your name has greater than 5 characters"

最佳答案

("Jesse" or "jesse")

上面的表达式测试"Jesse"是否评估为True。如果是这样,则表达式将返回它;否则,表达式将返回它。否则,它将返回"jesse"。该表达式等同于编写:
"Jesse" if "Jesse" else "jesse"

由于"Jesse"是非空字符串,因此它将始终求值为True并因此返回:
>>> bool("Jesse")  # Non-empty strings evaluate to True in Python
True
>>> bool("")  # Empty strings evaluate to False
False
>>>
>>> ("Jesse" or "jesse")
'Jesse'
>>> ("" or "jesse")
'jesse'
>>>

这意味着表达式:
name == ("Jesse" or "jesse")

基本上等同于编写此代码:
name == "Jesse"

为了解决您的问题,您可以使用 in operator:
# Test whether the value of name can be found in the tuple ("Jesse", "jesse")
if name in ("Jesse", "jesse"):

或者,您可以使用 name 小写str.lower的值,然后将其与"jesse"直接比较:
# This will also handle inputs such as "JeSSe", "jESSE", "JESSE", etc.
if name.lower() == "jesse":

10-01 11:07