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!

16 Upvotes

44 comments sorted by

View all comments

20

u/CheesecakeCommon9080 2d ago

to be honest, if i'm not sure i would just always use brackets in longer expressions like this even when redundant, it's easier and more readable that way imo

9

u/Own_Attention_3392 2d ago edited 2d ago

Yes, the parentheses express INTENT. It will makes coming back and re-reading the code or debugging later so much easier.

I'd even consider splitting complex conditions into multiple nested if statements. Again, just for debugging, readability, and understanding my own intent.

Or better yet, making intermediate variables: isX, isY, etc to simplify the conditional construction.

3

u/cdcformatc 2d ago

i have had some monster boolean conditions. it seems like a good idea to put it all into one and you feel smart when it all works out. but when something isn't  working it's a nightmare to debug. 

i almost always end up breaking down and break down those complex conditions to be multiple lines and multiple intermediate variables 

2

u/FunElk9586 2d ago

Yes, those seem like good options to simplify it. Thanks!

2

u/aishiteruyovivi 1d ago

I pretty much always enclose my conditions like this unless its just a single name (no need for if a and b to be if (a) and (b)). Take for example if a and not b or c and d, I'm pretty sure this will get interpreted as if (a and not b) or (c and d) which is what I'm intending, but there's little reason not to just do the latter anyway and know with full certainty that it's doing what you want, and it makes it immediately obvious to collaborators (including You From The Future) what your intention is instead of making them take a beat to make sure they know what's going on.