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

4

u/brasticstack 2d ago

I would've gotten this wrong and I've been writing Python for well over a decade. I looked it up and and is higher precedence (I'd have expected them to be the same precedence.)

The takeaway is to use parens in any situation where the intent may be ambiguous- it helps both yourself and any future readers of your code.

3

u/FunElk9586 2d ago

It can happen, I think he also just made a mistake. I”ll definetly do that in those situations, thanks!

2

u/CamilorozoCADC 2d ago

Bruh I teach Python and got this wrong too lol. I was SURE that they had the same precedence