简体   繁体   中英

Logical OR operation with -1

Why is the output different for the following logical operations that I tried in python?

-1 or 1
 1 or -1

First returns -1 and second returns 1

and and or are both lazy ; they evaluate operands until they can decide the result ( and stops at the first False operand; or stops at the first True operand). 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. 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.

Read the documentation :

The expression x or y first evaluates x ; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

Both first parts -1 and 1 are evaluated True and therefore returned. The second part is ignored.

The or operator short-circuits. It returns the first value that is True in a boolean context, or the last evaluated expression otherwise. -1 and 1 are both True in a boolean context, so you get the first number.

0 , None and all empty containers evaluate to 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.)

Python, like Perl, simply returns the first "true" value (where "true" means nonzero for numbers, non-empty for strings, not None, etc.)

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.

(see man )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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