I don't understand why the first one is true, does it short circuit when it sees True or?
>>> True or False and False
True
>>> True or False and True
True
I don't understand why the first one is true, does it short circuit when it sees True or?
>>> True or False and False
True
>>> True or False and True
True
In Python, and
has a higher precedence than or
, meaning that and
will bind first (search for Operator precedence
in the following section of the Python documentation, for example(1)).
Hence your two statements are equivalent to (despite your incorrect assertion that Python reads left to right):
True or (False and False)
True or (False and True)
And, regardless of what the result of the parenthesised sub-expression in those two expressions above, or
ing that with True
will give True
.
(1) The relevant parts of that link (the explanatory text and the initial part of the table) are included below for completeness, with my emphasis:
The following table summarizes the operator precedence in Python, from lowest precedence (least binding) to highest precedence (most binding). Operators in the same box have the same precedence. Unless the syntax is explicitly given, operators are binary. Operators in the same box group left to right (except for exponentiation, which groups from right to left).
Operator Description
-------- -----------
lambda Lambda expression
if – else Conditional expression
or Boolean OR
and Boolean AND
not x Boolean NOT
Thanks to PM 2Ring's comment: and
has higher precedence than or
. So Python will execute and
first, so
The first one is like this:
True or (False and False)
=> True or False
=> True
result of (False and False)
is False
and True or False
is True
.
The second one is like this:
True or (False and True)
=> True or False
=> True
result of (False and True)
is again False
and True or False
is True
.