Logical OR with -1

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

-1 or 1
 1 or -1

      

Returns first -1

and second returns1

+3


source to share


6 answers


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

nor or

restrict the value and type, they fall back to False

and True

, but rather return the last evaluated argument. This is sometimes useful, for example if s

is a string that should be replaced with a default value, if it is empty, the expression s or 'foo'

gives the required value.

+8


source


Read the documentation :



The expression x or y

evaluates first x

; if x

true, its value is returned; otherwise, the y

return value is evaluated and returned.

+7


source


Both the first parts are -1

both 1

evaluated True

and therefore returned. The second part is ignored.

+3


source


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 []
[]

      

+3


source


In a or

condition, if the first condition is true, the second is not evaluated,

+3


source


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 )

0


source







All Articles