我想检查变量是否具有多个值之一。我很困惑为什么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"
答案 0 :(得分:53)
("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"):
或者,您可以使用str.lower
小写name
的值,然后直接将其与"jesse"
进行比较:
# This will also handle inputs such as "JeSSe", "jESSE", "JESSE", etc.
if name.lower() == "jesse":
答案 1 :(得分: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'
,正如您所观察到的那样。
答案 2 :(得分:6)
or
运算符返回第一个操作数(如果为真),否则返回第二个操作数。因此,在您的情况下,您的测试等同于if name == "Jesse"
。
or
的正确应用是:
if (name == "Jesse") or (name == "jesse"):
答案 3 :(得分:5)
如果您不想进行不区分大小写的比较,请使用lower
或upper
:
if name.lower() == "jesse":