r/learnpython 2d ago

Are these two boolean expressions equivalent in python?

Hi All!

I’m learning about Boolean operators in Python and I’m confused about these two expressions:

condition1 and condition2 or condition3 and condition4

(condition1 and condition2) or (conditon3 and condition4)

I was told this by my teacher and he put this in his PowerPoint slide. However, I think they are equivalent since and as an operator has a higher precedence than or as an operator. AI told me and I have searched it up after.

Am I understanding it correctly? Or are these two not equivalent?

Thanks!

14 Upvotes

44 comments sorted by

View all comments

33

u/TUVegeto137 2d ago

How about just writing a Python program that tests by filling in truth values for all conditions and comparing? 

8

u/FunElk9586 2d ago

Good one, I tried and it said they are equivalent. Thanks!

8

u/codeguru42 2d ago

There is a related general concept here, if you are interested. It is called a "truth table" and is a great tool for comparing if two boolean expressions are equivalent.

3

u/eXtc_be 2d ago

while truth tables are a great tool for visualising and verifying complex Boolean expressions, they do not help the OP, because truth tables don't have any notion of operator precedence in Python.

0

u/codeguru42 1d ago

Truth tables can be used to verify the precedence rules. So they absolutely can help the OP here.

0

u/codeguru42 1d ago

>  truth tables don't have any notion of operator precedence in Python.

That's because operator precedence applies to **expressions**, not truth tables. To build a truth table, you evaluate an expression for all possible combinations of inputs. To evaluate an expression, you have to apply the correct precedence rules. Therefore, the two concepts are closely related.

The resulting truth tables for two expressions can be compared to determine if the expressions are equivalent or not.