Python 中的 OR 行为: [英] OR behaviour in python:
问题描述
我编写了以下代码,如果传递的数字是 1、0 或 2 的字符串表示,我想要做的就是打印 yes,对于其他所有内容都为 false:
I have written the following piece of code, all i want to do is print a yes for if the number passed is a string representation of 1, 0 or 2 and for everything else a false:
number=raw_input()
if number is "1" or "0" or "2":
print "Yes"
else:
print "no"
我知道如何使预期的逻辑工作,但我只是想让 need 知道为什么它会为我传递给 raw_input 的任何数字打印 yes.我希望答案尽可能详细,因为我不明白为什么会失败,这对我来说似乎足够 pythonic
I know how to make the intended logic work, but i just want need to know why it prints yes for any number i pass to raw_input. I'd like the answer to be as detailed as possible, because i cant understand why it would fail, it seems pythonic enough to me
推荐答案
问题是你的代码对于 Python 来说是这样的:
The problem is that your code, to Python, reads like this:
if (number is "1") or "0" or "2":
并且由于任何非空字符串的计算结果为 True
,因此它始终为 True
.
And as any non-empty string evaluates to True
, it's always True
.
做你想做的事,一个很好的语法是:
To do what you want to do, a nice syntax is:
if number in {"1", "0", "2"}:
注意我在这里使用了一个集合——虽然在这种情况下(只有三个值)检查集合比列表更快,因为集合的成员资格测试是 O(1)而不是 O(n).
Note my use of a set here - while it doesn't matter too much in this case (with only three values) checking against a set is faster than a list, as a membership test for a set is O(1) instead of O(n).
这样写起来更好更容易:
This is simply a nicer and easier of writing this:
if number == "1" or number == "0" or number == "2":
这就是你想要的.
请注意,在进行值比较时,您应该始终使用 ==
而不是 is
- is
是身份检查(这两个值是同一个对象).通常,您应该将 is
用于诸如 is True
或 is None
之类的东西.
Note when making a comparison for value you should always use ==
not is
- is
is an identity check (the two values are the same object). Generally you should use is
for stuff like is True
or is None
.
如果你想把它当作一个数字来处理,你可以这样做:
If you wanted to handle this as a number, you could do something like this:
try:
value = int(number)
except ValueError:
value = None
if value is not None and 0 <= value <= 2:
...
在您想与大量数字进行比较的情况下,这可能更有用.请注意我使用 Python 有用的比较链(0 <= value <= 2
而不是 0 <= value 和 value <= 2
).
Which could be more useful in situations where you want to compare to a large range of numbers. Note my use of Python's useful comparison chaining (0 <= value <= 2
rather than 0 <= value and value <= 2
).
这篇关于Python 中的 OR 行为:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!