[英]Logical OR operation with -1
Why is the output different for the following logical operations that I tried in python? 为什么我在python中尝试的以下逻辑操作的输出不同?
-1 or 1
1 or -1
First returns -1
and second returns 1
First返回-1
,第二个返回1
and
and or
are both lazy ; and
or
都是懒惰的 ; they evaluate operands until they can decide the result ( and
stops at the first False
operand; or
stops at the first True
operand). 它们会评估操作数,直到它们可以决定结果( and
在第一个False
操作数处停止; or
在第一个True
操作数处停止)。 They return the last operand evaluated, as noted in the documentation : 它们返回评估的最后一个操作数,如文档中所述 :
Note that neither
and
noror
restrict the value and type they return toFalse
andTrue
, but rather return the last evaluated argument. 需要注意的是既不and
也不or
限制值并键入他们返回False
和True
,而是返回最后一个变量。 This is sometimes useful, eg, ifs
is a string that should be replaced by a default value if it is empty, the expressions or 'foo'
yields the desired value. 这有时是有用的,例如,如果s
是一个字符串,如果它是空的,则应该用默认值替换,表达式s or 'foo'
产生所需的值。
Read the documentation : 阅读文档 :
The expression
x or y
first evaluatesx
; 表达式x or y
首先评估x
; ifx
is true, its value is returned; 如果x
为真,则返回其值; otherwise,y
is evaluated and the resulting value is returned. 否则,将评估y
并返回结果值。
Both first parts -1
and 1
are evaluated True
and therefore returned. 两个第一部件-1
和1
被评估True
,并因此返回。 The second part is ignored. 第二部分被忽略了。
The or
operator short-circuits. or
操作员短路。 It returns the first value that is True
in a boolean context, or the last evaluated expression otherwise. 它返回布尔上下文中的第一个值True
,否则返回最后一个计算的表达式。 -1
and 1
are both True
in a boolean context, so you get the first number. 在布尔上下文中, -1
和1
都是True
,因此您获得第一个数字。
0
, None
and all empty containers evaluate to False
. 0
, None
和所有空容器的计算结果为False
。
For example: 例如:
>>> 0 or 5
5
>>> '' or []
[]
在or
条件,如果第一个条件为真,第二不评价
I think the OP expects the return value of 'or' to be either True or False (as would be the case for boolean operators in some other languages.) 我认为OP期望'或'的返回值为True或False(在某些其他语言中布尔运算符就是这种情况。)
Python, like Perl, simply returns the first "true" value (where "true" means nonzero for numbers, non-empty for strings, not None, etc.) 像Perl一样,Python只返回第一个“true”值(其中“true”表示数字非零,非字符串表示非空,等等)
Similarly, 'and' returns the last value if and only if both are "true". 类似地,当和仅当两者都是“真”时,'和'返回最后一个值。
He would probably be even more surprised by the result of something like 他可能会对类似的结果感到更加惊讶
{'x':1} or [1,2,3]
Perl programmers often use this construct idiomatically (as in open(FILE, "foo.txt") || die
; I don't know if that's as common in Python. Perl程序员经常以惯用方式使用这个结构(如open(FILE, "foo.txt") || die
;我不知道这在Python中是否常见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.