0

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
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
  • Also [this](https://stackoverflow.com/questions/51784005/python-or-and-operator-precedence-example) and [this](https://stackoverflow.com/questions/16679272/priority-of-the-logical-statements-not-and-or-in-python) and many more. – TigerhawkT3 Feb 03 '19 at 08:26

2 Answers2

3

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, oring 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

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
2

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.

letsintegreat
  • 3,328
  • 4
  • 18
  • 39
Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
  • 7
    You should mention that `and` has higher precedence than `or`, similar to `*` having higher precedence than `+`. – PM 2Ring Feb 03 '19 at 07:55