r/learnpython • • 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!

15 Upvotes

49 comments sorted by

View all comments

Show parent comment

1

u/[deleted] 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’