为什么是“否”?作为以下 python 代码中的 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."
I cannot for the life of me understand why I can't get to the "else" statement no matter what I type. Any insight would be much appreciated. Am I not allowed to use more than one "or"?
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."
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为在Python中
相当于
并且非空字符串为true。
您应该将代码更改为
or ,以接受大小写的变化:
或者甚至可以使用正则表达式。
在 Python 2.7 及更高版本中,您甚至可以使用集合,在使用
in
时,集合比元组更快。但你确实会从 python 3.2 及更高版本中获得性能提升,因为在实现集合垃圾之前,它并不像元组那样优化。
Because in python
is equivalent to
and a nonempty string is true.
You should change your code to
or, to accept variations in capitalization:
or maybe even use a regex.
In Python 2.7 and more, you can even use sets, which are fasters than tuples when using
in
.But you really will get the perf boost from python 3.2 and above, since before the implementation of sets litterals is not as optimised as tuples ones.
就像上面的答案所说,当您将
str
类型转换为bool
时,只有空字符串返回 false:因此,当您说:
将被评估为:
该语句 这个故事的寓意是,在编辑代码时运行解释器是个好主意,这样您就可以在将复杂表达式组合在一起之前尝试小块复杂的表达式:)
Like the answer above says, when you cast a
str
type to abool
only the empty string returns false:So, when you say:
that statement will be evaluated to:
The moral of the story is that it's good idea to have an interpreter running while you're editing code then you can try out small chunks of complex expressions before you put them together :)