Logical operators in Python
that is well documented:
x or y if x is false, then y, else x
x and y if x is false, then x, else y
both short-circuit (e.g. or
will not evaluate y
if x
is truthy).
the documentation also states what is considered falsy (False
, 0
, None
, empty sequences/mappings, ...) - everything else is considered truthy.
a few examples:
7 and 'a' # -> 'a'
[] or None # -> None
{'a': 1} or 'abc'[5] # -> {'a': 1}; no IndexError raised from 'abc'[5]
False and 'abc'[5] # -> False; no IndexError raised from 'abc'[5]
note how the last two show the short-circuit behavior: the second statement (that would raise an IndexError
) is not executed.
your statement that the operands are boolean is a bit moot. python does have booleans (actually just 2 of them: True
and False
; they are subtypes of int). but logical operations in python just check if operands are truthy or falsy. the bool
function is not called on the operands.
the terms truthy and falsy seem not to be used in the official python documentation. but books teaching python and the community here do use these terms. there is a discussion about the terms on english.stackexchange.com and also a mention on wikipedia.
This is because of the short-circuit evaluation method.
For the and
, all of the clauses must be True
, so all of them must be evaluated. Once a False
is encountered, the whole thing evaluates to False
, we don't even need to evaluate the next ones.
>>> 1 and 2 2 >>> 2 and 1 1 >>> 1 and 2 and 3 3 >>> 1 and 0 and 2 0 >>> 0 and 1 and 2 0
But for or
, any of the clauses being evaluated to True
is enough for the whole thing to be True
. So once it finds something to be True
, the value of the whole thing is decided to be True
, without even evaluating the subsequent clauses.
>>> 0 or 1 1 >>> 1 or 0 1 >>> 1 or 2 1 >>> 2 or 1 2 >>> 0 or 0 or 1 1 >>> 0 or 1 or 2 1