Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird boolean evaluation in python 3.8

Tags:

python

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?

like image 252
codeKashmir Avatar asked Jan 31 '26 02:01

codeKashmir


2 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
like image 131
Silvio Mayolo Avatar answered Feb 03 '26 11:02

Silvio Mayolo


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
like image 43
Matt McCarthy Avatar answered Feb 03 '26 10:02

Matt McCarthy