Weird boolean evaluation in python 3.8

Viewed 58

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?

3 Answers

and binds tighter than or, so what you're writing is actually

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

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

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

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
Related