Reputation: 468
How is evaluated the Python code:
not not True or False and not True
As of myself, I have two guesses:
Method 1:
Step Code
1 not not True or False and not True
2 not False or False and False
3 True or False and False
4 True and False
5 False
Method 2:
Step Code
1 not not True or False and not True
2 not False or False and False
3 True or False
4 True
Upvotes: 0
Views: 373
Reputation: 51980
From the table of Python's operators precedence:
or
has lower precedence thanand
which in its turn has lower precedence not
According to that:
not not True or False and not True
Is the equivalent to
((not (not True)) or (False and (not True)))
EDIT: As noticed by Martijn Pieters in a comment below, worth mentionning that Python has short-circuits operators. That means that and
and or
are guaranteed to be evaluated left-to-right and that:
or
is True
the right term is never evaluated (as the result of True or whatever
is True
in boolean logic)and
is False
the right term is never evaluated (as the result of False and whatever
is False
in boolean logic)So, given your example:
The first step is to evaluate not True
to False
:
((not (not True)) or (False and (not True)))
^^^^^^^^
False
Then not False
is evaluated to True
:
((not False ) or (False and (not True)))
^^^^^^^^^^^^^^
True
As we no have True or ...
Python stops evaluation immediately with the result True
:
( True or (False and (not True)))
^^^^^^^^^^^^^^ ......................
True (right-hand side ignored)
Upvotes: 3
Reputation: 95948
To understand that, you should see the Operator precedence.
Your code is equivalent to:
((not (not True)) or (False and (not True)))
Now you should be able to tell what answer is correct and why.
Upvotes: 0