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
noror
restrict the value and type they return toFalse
andTrue
, but rather return the last evaluated argument. 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.
Read the documentation :
The expression
x or y
first evaluatesx
; ifx
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.