为什么"No"作为raw_input在以下python代码中返回TRUE?

one*_*cah 4 python boolean

我不能为我的生活理解为什么无论我输入什么我都无法得到"别的"陈述.任何见解都会非常感激.我不允许使用多个"或"?

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."
Run Code Online (Sandbox Code Playgroud)

sve*_*rre 23

因为在python中

if tunnel == "Y" or "Yes" or "Yea" or "Si" or "go" or "Aye" or "Sure":
Run Code Online (Sandbox Code Playgroud)

相当于

if (tunnel == "Y") or ("Yes") or ("Yea") or ("Si") or ("go") or ("Aye") or ("Sure"):
Run Code Online (Sandbox Code Playgroud)

并且非空字符串为true.

您应该将代码更改为

if tunnel in ("Y", "Yes", "Yea", "Si", "go", "Aye", "Sure"):
Run Code Online (Sandbox Code Playgroud)

或者,接受大写字母的变化:

if tunnel.lower() in ("y", "yes", "yea", "si", "go", "aye", "sure"):
Run Code Online (Sandbox Code Playgroud)

或者甚至可以使用正则表达式.

在Python 2.7及更高版本中,您甚至可以使用集合,这些集合在使用时比元组更紧凑in.

if tunnel.lower() in {"y", "yes", "yea", "si", "go", "aye", "sure"}:
Run Code Online (Sandbox Code Playgroud)

但是你真的会从python 3.2及更高版本中获得性能提升,因为在集合实现之前,litterals并不像元组那样优化.

  • 或者也许`if tunnel.lower()in('y',...)` (3认同)