r/learnpython • u/FunElk9586 • Sep 12 '26
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!
22
u/CheesecakeCommon9080 Sep 12 '26
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
8
u/Own_Attention_3392 Sep 12 '26 edited Sep 12 '26
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.
2
3
u/cdcformatc Sep 12 '26
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/aishiteruyovivi Sep 13 '26
I pretty much always enclose my conditions like this unless its just a single name (no need for
if a and bto beif (a) and (b)). Take for exampleif a and not b or c and d, I'm pretty sure this will get interpreted asif (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.
21
u/latkde Sep 12 '26
Per the Python language specification , an "or" expression consists of "and"-level expressions. That is, you're right, the "and" binds more tightly, and the two examples should be equivalent.
https://docs.python.org/3/reference/expressions.html#boolean-operations
In practice, this doesn't matter. As a professional Python developer, I always use parentheses in such a case to remove any risk of confusion.
2
u/FunElk9586 Sep 12 '26
Good to know that my understanding was correct and thank you! I”ll use parentheses in such cases as well.
1
u/davideogameman Sep 12 '26
+1, code that's clear & correct is pretty much always easier to read & maintain than code that is correct but requires uncommon knowledge of language or library details.
6
u/brasticstack Sep 12 '26
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 Sep 12 '26
It can happen, I think he also just made a mistake. I”ll definetly do that in those situations, thanks!
2
u/CamilorozoCADC Sep 12 '26
Bruh I teach Python and got this wrong too lol. I was SURE that they had the same precedence
2
u/xelf Elf Sep 12 '26
It needs to be pointed out that they are equivalent in python. But that does not hold true in many other languages. You will see the () used for clarity a lot, especially by programmers that use multiple languages.
2
u/FunElk9586 Sep 13 '26
That’s good to know. I didn’t know it differs. That makes using parentheses for clarity make even more sense.
1
u/le_sasch Sep 15 '26
In my experience all common languages implement the same precedence (not - and - or) which are also common when writing down boolean algebra in electronics or philosophy.
1
u/xelf Elf Sep 15 '26
Actually there's not a lot when you start looking. Languages that evaluate left to right like APL or bash, or ones that use prefix notation like lisp and clojure. When I actually started looking into it there was less than I remembered.
2
u/Expensive-Bear-1376 Sep 12 '26
I'd like to see that PowerPoint slide, to see that he wrote exactly that and you didn't paraphrase and remove the difference.
2
u/FunElk9586 Sep 12 '26
He did make a typo, on the first line it should be ofcourse condition3 instead of condition
0
1
u/This_Growth2898 Sep 12 '26
According to the documentation, boolean And has a higher precedence than boolean Or, so yes, they are equivalent. First, expressions with and will be calculated; next, the central or will be. If your teacher doesn't agree with this, ask him to provide specific values for variables that make the expression different.
1
u/FunElk9586 Sep 12 '26
Yes, I will talk to him about it. However, I think he will agree and just made a mistake. Otherwise I will ask him.
1
u/gdchinacat Sep 12 '26
The vast way to learn this is to use the REPL and try it out. Spending 20 minutes trying various permutations will teach you it far better than reading a dozen posts here on Reddit. If you want to search for documentation look up “python order of precedence”.
1
u/FunElk9586 Sep 13 '26
Yes.Trying out is always better, but I was just doubting myself. I have done and will do that
1
Sep 12 '26
This is easy enough to just check, but can also be proven from `and` and `or` operator precedence
import itertools
class UndefinedBool:
def __bool__(self):
raise TypeError("Undefined bool value")
class ConditionArray:
def __init__(self, *args):
self.conditions = [*args]
def __repr__(self):
return f"{hash(self):x} {self.conditions}"
def at(self, idx):
try:
return self.conditions[idx]
except IndexError:
return UndefinedBool()
def expr1(carr: ConditionArray) -> bool:
return carr.at(0) and carr.at(1) or carr.at(2) and carr.at(3)
def expr2(carr: ConditionArray) -> bool:
return (carr.at(0) and carr.at(1)) or (carr.at(2) and carr.at(3))
if __name__ == "__main__":
fail_combs = []
for arr in itertools.product((0, 1), repeat=4):
carr = ConditionArray(*arr)
print(carr)
if not (expr1(carr) == expr2(carr)):
fail_combs.append(carr)
print(len(fail_combs))
7fb51ba912b [0, 0, 0, 0]
7fb51ba7909 [0, 0, 0, 1]
7fb51ba791d [0, 0, 1, 0]
7fb51bbbd94 [0, 0, 1, 1]
7fb51bbbfa8 [0, 1, 0, 0]
7fb51ba7549 [0, 1, 0, 1]
7fb51ba539b [0, 1, 1, 0]
7fb51ba53ac [0, 1, 1, 1]
7fb51ba4ea5 [1, 0, 0, 0]
7fb51ba4ec5 [1, 0, 0, 1]
7fb51ba718b [1, 0, 1, 0]
7fb51ba719a [1, 0, 1, 1]
7fb51ba3821 [1, 1, 0, 0]
7fb51ba3805 [1, 1, 0, 1]
7fb51ba0cd5 [1, 1, 1, 0]
7fb51bb4699 [1, 1, 1, 1]
02
u/FunElk9586 Sep 12 '26
At first I didn’t understand the code because I haven’t learned most of this yet. However, I understand the point now. You tested all 16 possible combinations and got 0 differences, so both expressions always give the same result. Right? Thanks for taking the time.
1
Sep 13 '26
Yes, I essentially build a truth table. It's more complex than it needs to be. I've been writing C++ lately and wanted to make a specific input type for those functions, but typically in python you'd just pass a list or an array.
UndefinedBool's only purpose is to have variables that fail when you try to get their truth value. It was used for debugging, but now seems useless.
ConditionArray is supposed to be a type storing truth values, but tbh is unfinished and doesn't do meaningfully more than a plain list. Python is weakly typed, but I think when the function's input type tells you something meaningful it makes the code more readable.
Main logic is just generating all 16 possible values and counting ones which evaluate to different value in expr1 and expr2. Just now I noticed that the check is pretty weird, rather than `not (x == y)` I should've used `x != y`
here's a simpler version that does the same
import itertools def expr1(carr: list[bool]) -> bool: return carr[0] and carr[1] or carr[2] and carr[3] def expr2(carr: list[bool]) -> bool: return (carr[0] and carr[1]) or (carr[2] and carr[3]) if __name__ == "__main__": fails = 0 for conditions in itertools.product((True, False), repeat=4): if expr1(list(conditions)) != expr2(list(conditions)): fails += 1 print(fails)1
u/FunElk9586 Sep 13 '26
Okay, thank you so much for explaining. That’s okay I can change it to ‘x != y’
1
u/Brian Sep 15 '26
You can test it out by trying the entire truth table. Eg:.
for a,b,c,d in itertools.product(*[[True, False]]*4):
assert (a and b or c and d) == ((a and b) or (c and d))Which will indeed show that they're equivalent. Though I would recommend putting in the brackets: you typically do want to make it as clear as possible what the intended meaning is, rather than relying on knowing all the details of precedence.
1
u/timrprobocom Sep 12 '26
and has higher precedence than or. That's really all you need to know to answer the question
1
u/cdcformatc Sep 12 '26
and hass a higher precedence than or so those two lines are logically equivalent
1
0
34
u/TUVegeto137 Sep 12 '26
How about just writing a Python program that tests by filling in truth values for all conditions and comparing?