'Weird boolean evaluation in python 3.8

While trying to debug an issue, I hit some weird boolean evaluation happening in python. Below is the sample shell result.


In [4]: True or False and False
Out[4]: True

In [5]: False or True and False
Out[5]: False

What exactly is happening here. Shouldn't both evaluate to the same result?



Solution 1:[1]

and takes precedence over or. See what happens when we evaluate the and first?

>>> (True or False and False) == (True or False)
True
>>> (False or True and False) == (False or False)
True

Solution 2:[2]

Based on the python order of precedence AND has higher precedence than OR hence AND will get evaluated first followed by OR.

So it evaluates to something like below

(True or (False and False)) = True
(False or (True and False)) = False

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matt McCarthy
Solution 2 Praburaj