Bsonjin
Bsonjin

Reputation: 468

Python True/False for the following code

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

Answers (2)

Sylvain Leroux
Sylvain Leroux

Reputation: 51980

From the table of Python's operators precedence:

  • or has lower precedence than
  • and which in its turn has lower precedence
  • than 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:

  • If the left-term of an or is True the right term is never evaluated (as the result of True or whatever is True in boolean logic)
  • If the left-term of an 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:

  1. The first step is to evaluate not True to False:

     ((not (not True)) or (False and (not True)))
            ^^^^^^^^
             False
    
  2. Then not False is evaluated to True:

     ((not    False  ) or (False and (not True)))
       ^^^^^^^^^^^^^^
           True
    
  3. 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

Maroun
Maroun

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

Related Questions