James T. James T. - 2 months ago 5
Python Question

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.

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


True is printed

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


False is printed

Here's my break of the logic:

True or False => True

True and False => False

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

Why does this happen?

Answer

This is because of short circuiting. In the first example, if statements are evaluated left to right. Python encounters True and sees no need to move on as the condition is already true no matter what. In your example:

if True or False and False:

This line, Python sees an OR operator. Next, it evaluates the leftmost condition. Since it's True, then the whole condition has to be true. It then short-circuits and prints 'True'.

In the second example you add grouping and True or False is True, True and False is False.

if (True or False) and False:

(True or False) gives True because at least one is True. True and False gives False because not both are True.

Comments