为什么下面的python代码中"no"作为raw_input返回TRUE?
我真搞不懂,为什么无论我输入什么,都无法到达“else”语句。希望能得到一些帮助。我是不是不可以用多个“或”呢?
print "Do you want to go down the tunnel? "
tunnel = raw_input ("> ")
if tunnel == "Y" or "Yes" or "Yea" or "Si" or "go" or "Aye" or "Sure":
print "You found the gold."
else:
print "Wrong answer, you should have gone down the tunnel. There was gold down there."
2 个回答
-1
就像上面的回答说的,当你把一个 str
类型转换成 bool
类型时,只有空字符串会返回假(false):
>>> bool("")
False
>>> bool("No")
True
>>>
所以,当你说:
if (tunnel == 'y') or 'foobar':
print('woo')
这句话会被计算成:
if (tunnel == 'y') or True:
print('woo')
这个故事的道理是,在你编辑代码的时候,最好有一个解释器在运行,这样你可以在把复杂的表达式组合在一起之前,先试试小块的代码 :)
23
因为在Python中
if tunnel == "Y" or "Yes" or "Yea" or "Si" or "go" or "Aye" or "Sure":
等同于
if (tunnel == "Y") or ("Yes") or ("Yea") or ("Si") or ("go") or ("Aye") or ("Sure"):
而且非空字符串被视为真。
你应该把你的代码改成
if tunnel in ("Y", "Yes", "Yea", "Si", "go", "Aye", "Sure"):
或者,为了接受大小写的不同:
if tunnel.lower() in ("y", "yes", "yea", "si", "go", "aye", "sure"):
或者甚至可以使用正则表达式。
在Python 2.7及更高版本中,你甚至可以使用集合,这在使用in
时比元组更快。
if tunnel.lower() in {"y", "yes", "yea", "si", "go", "aye", "sure"}:
不过,你真的会在Python 3.2及以上版本中获得性能提升,因为在此之前,集合字面量的实现没有元组那么优化。