James T.
James T.

Reputation: 978

How are conditional statements with multiple conditions evaluated?

I'd expect the following two code blocks to be evaluated the same way, but it would seem that is not the case. For example, with this:

if True or False and False:
    print('True')                                                               
else:                                                                           
    print('False')

True is printed. But with this:

if (True or False) and False:
    print('True')
else:                                                                           
    print('False')

False is printed. Here's my breakdown of the logic:

By substitution, (True or False) and False = True and False = False.

Why does this happen?

Upvotes: 1

Views: 4036

Answers (4)

IVAN PAKPAHAN
IVAN PAKPAHAN

Reputation: 1

The first condition returns false. You know that a value of false will not run the code block below it.

Upvotes: 0

Andrew Li
Andrew Li

Reputation: 57982

This is because of operator precedence. Per the Python 2.x and 3.x docs, the and operator has higher precedence than the or operator. Also, have a look at the boolean truth table:

enter image description here

That means in your expression:

if True or False and False:

In the expression, False and False is grouped together because of precedence. That means Python evaluates it as:

if True or (False and False):

Now, it's evaluated left to right. Since the first condition is True, it short-circuits and skips the second condition and evaluates to True printing 'True'. (This short-circuits because if the first side is true, it has to be true.)

Now in your second example:

if (True or False) and False:

This makes True or False evaluate first, which gives True. Then it does True and False which is False, printing 'False'.

>>> print(True or False)
True
>>> print(True and False)
False

Upvotes: 3

notovny
notovny

Reputation: 131

Standard Order of operations gives and precedence over or, so the first statement True or False and False is logically equivalent to

True or (False and False)

This evaluates to True.

The second statement is

(True or False) and False

This evaluates to False.

Upvotes: 1

101
101

Reputation: 8999

(True or False) evaluates to True. Therefore (True or False) and False evaluates to True and False, which evaluates to False.

This answer explains the rules for boolean evaluation quite well: https://stackoverflow.com/a/16069560/1470749

Upvotes: 1

Related Questions