我不能为我的生活理解为什么无论我输入什么我都无法得到“别的”陈述。任何见解都会非常感激。我不允许使用多个“或”?
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."
答案 0 :(得分: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及更高版本中获得性能提升,因为在集合实现之前,litterals并不像元组那样优化。
答案 1 :(得分:-1)
与上面的答案一样,当您将str
类型转换为bool
时,只有空字符串返回false:
>>> bool("")
False
>>> bool("No")
True
>>>
所以,当你说:
if (tunnel == 'y') or 'foobar':
print('woo')
该语句将被评估为:
if (tunnel == 'y') or True:
print('woo')
故事的寓意是,在编辑代码时运行解释器是个好主意,然后在将它们放在一起之前可以尝试一小部分复杂的表达式:)