In Python, nonzero numbers are counted as true for the purposes of boolean expressions, and zero is counted as false. So even though both and
and or
are normally used with the booleans True
and False
, they can be used with numbers too.
The issue is: what is the value of an expression like 10 and 3
, where both of the values evaluate to true? In C, which has similar integer-as-boolean semantics, the value of 10 && 3
is 1, the most commonly used true value. However, in Python the value of this expression is 3, the second half of the and expression. This makes sense because and short-circuits, meaning that 0 and 3
is 0, so and
has "take the first value if it's false, the second otherwise" semantics.
What about the expression you posted? By operator precedence, it's the same as
(22 and 333/12) or 1
The value of 22 and 333/12
is 333/12
, which is 27. Since the or operator short-circuits, the Python interpreter takes the first true value when evaluating 27 or 1
, and gets 27.