简体   繁体   English

使用-1的逻辑OR运算

[英]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 nor or restrict the value and type they return to False and True , but rather return the last evaluated argument. 需要注意的是既不and也不or限制值并键入他们返回FalseTrue ,而是返回最后一个变量。 This is sometimes useful, eg, if s is a string that should be replaced by a default value if it is empty, the expression s or 'foo' yields the desired value. 这有时是有用的,例如,如果s是一个字符串,如果它是空的,则应该用默认值替换,表达式s or 'foo'产生所需的值。

Read the documentation : 阅读文档

The expression x or y first evaluates x ; 表达式x or y首先评估x ; if x 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. 两个第一部件-11被评估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. 在布尔上下文中, -11都是True ,因此您获得第一个数字。

0 , None and all empty containers evaluate to False . 0None和所有空容器的计算结果为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中是否常见。

(see man ) (见男人

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM