34

我想检查一个变量是否具有多个值之一。我很困惑为什么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"
4

4 回答 4

52
("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运算符

# Test whether the value of name can be found in the tuple ("Jesse", "jesse")
if name in ("Jesse", "jesse"):

name或者,您可以将with的值小写str.lower,然后"jesse"直接比较:

# This will also handle inputs such as "JeSSe", "jESSE", "JESSE", etc.
if name.lower() == "jesse":
于 2013-08-13T15:02:28.640 回答
10
if name in ("Jesse", "jesse"):

将是正确的方法。

虽然,如果你想使用or,声明将是

if name == 'Jesse' or name == 'jesse':

>>> ("Jesse" or "jesse")
'Jesse'

评估为'Jesse',因此您基本上不会测试'jesse'何时执行,因为正如您观察到的那样if name == ("Jesse" or "jesse"),它仅测试与 的相等性'Jesse'而不测试。'jesse'

于 2013-08-13T15:00:49.353 回答
6

如果您想要不区分大小写的比较,请使用loweror upper

if name.lower() == "jesse":
于 2013-08-13T15:02:00.230 回答
6

or如果为真,则运算符返回第一个操作数,否则返回第二个操作数。因此,在您的情况下,您的测试等效于if name == "Jesse".

的正确应用or是:

if (name == "Jesse") or (name == "jesse"):
于 2013-08-13T15:02:10.050 回答