I want to know which determines the output like not in this case applies to first condition only or both

29 views Asked by At
x=(not (5==5) and (10<12))
print(x)

when executing. not negates the first expression or both?

In my opinion "not" should be executed with (5==5) only but my colleague says it will affect the whole expression in the bracket like (5==5) and (10<12).

2

There are 2 answers

2
fuad ashraful On

You can follow the approach I use. Instead of and we can place or operation to verify the answer. The result shows True . As the result is true so we can say that not (5==5) applies first. If the not operation runs with ((5==5) or (10<12)) then final result should be False. Hope it will help to understand.

enter image description here

3
tdelaney On

It all comes down to Operator precedence. Looking at the table, not is higher than and so it goes first. So you are right, the not goes with the (5==5).

You can test with a simpler example.

>>> not 1 and 2
False

Python calculated not 1 and since it's False, it short-circuited the and operation.

>>> not 0 and 2
2

Python calculated not 0 and since it is True, continued through the and.

>>> not (0 and 2)
True

Your colleague's prediction was wrong.

>>> (not 0) and 2
2

Your prediction worked!