Logical OR with -1
and
and or
are lazy; they evaluate the operands until they can decide the result ( and
stops at the first operand False
; or
stops at the first operand True
). They return the last operand as stated in the documentation :
Note that neither does
and
noror
restrict the value and type, they fall back toFalse
andTrue
, but rather return the last evaluated argument. This is sometimes useful, for example ifs
is a string that should be replaced with a default value, if it is empty, the expressions or 'foo'
gives the required value.
source to share
Read the documentation :
The expression
x or y
evaluates firstx
; ifx
true, its value is returned; otherwise, they
return value is evaluated and returned.
source to share
Operator short circuits or
. It returns the first value that is True
in a boolean context, or the last expression evaluated otherwise. -1
and 1
are True
in boolean context, which is why you get the first number.
0
, None
And all the empty containers are evaluated before False
.
For example:
>>> 0 or 5
5
>>> '' or []
[]
source to share
I think the OP expects the return value 'or' to be either True or False (as is the case with boolean operators in some other languages.)
Python, like Perl, simply returns the first "true" value (where "true" means nonzero for numbers, not empty for strings, not None, etc.)
Likewise, '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 this is common in Python.
(see man )
source to share