Python 布尔帮助!
我有这样的代码:
if (X or Y) == ("Cat" or "Dog" or "Fish" or "Bird"):
print X, Y
仅当 X == "Cat"
时才有效。有人知道我的错误吗?
I have a code like this:
if (X or Y) == ("Cat" or "Dog" or "Fish" or "Bird"):
print X, Y
It is only working if X == "Cat"
. Does anyone know my mistake here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为你想要这样的逻辑:
在你的代码中,表达式(“Cat”或“Dog”或“Fish”或“Bird”)被视为逻辑表达式,我确信你不想要这种逻辑表达式。碰巧这个表达式的计算结果为“Cat”,这解释了您观察到的行为。
这些是对字符串的逻辑运算。非空字符串被视为 True 值。空字符串被视为 False。 Python 的逻辑运算符返回与操作数相同类型的值(假设两个操作数的类型相同)。短路评估在此处解释了
or
和and
的行为。无论如何,对字符串执行逻辑运算没有什么意义!
I think you want logic like this:
In your code the expression ("Cat" or "Dog" or "Fish" or "Bird") is treated as a logical expression which I'm sure you don't want. As it happens this expression evaluates to "Cat" which explains your observed behaviour.
These are logical operations on strings. Non-empty strings are regarded as True values. Empty strings are regarded as False. Python's logical operators return values of the same type as the operands (assuming both operands are the same type). Short-circuit evaluation explains the behaviour for
or
andand
here.In any case, it makes very little sense to perform logical operations on strings!
Python 中的
or
运算符返回其第一个参数,如果它是 “trucy”,或其第二个参数。只要X
为“,比较右侧的计算结果始终为"Cat"
,左侧的计算结果始终为X
休战”。获得您正在寻找的逻辑的最简洁的方法是
The
or
operator in Python returns its first argument if it is "trucy", or its second argument else. The right-hand side of your comparison always evaluates to"Cat"
, and the left-hand side toX
as long asX
is "trucy".The most concise way to get the logic you are looking for is
发生的情况是,您正在计算
X 或 Y
,只给出X
。然后,您计算出Cat 或 Dog 或..
,只得到Cat
,因为它不是 0。你想要的是:
What happens is you are working out
X or Y
, giving you justX
. Then, you're working outCat or Dog or..
, giving you justCat
, since it's non-0.What you want is:
你的问题在于 Python 计算
or
的方式。如果 a 为真(非零、非空字符串或对象),a 或 b
返回 a;否则返回b。因此,"string" 或 b
将始终计算为"string"
。因此
“Cat”或“Dog”或“Fish”或“Bird”
将始终评估为“Cat”
,并且
X 或 Y
将始终计算为X
(只要 X 是由一个或多个字符组成的字符串)并且
X=="Cat"
显然只有当 X 是“Cat”时才为真。Your problem is in the way Python evaluates
or
. If a is truthy (not-zero, or a non-empty string, or an object)a or b
returns a; otherwise it returns b. So"string" or b
will always evaluate to"string"
.So
"Cat" or "Dog" or "Fish" or "Bird"
will always evaluate to"Cat"
,and
X or Y
will always evaluate toX
(so long as X is a string of one or more characters)and
X=="Cat"
is obviously only true when X is "Cat".