Sanon
Sanon

Reputation: 73

I don't understand operator precedence in python True and False or True

It says in python 2.7 docs that or has lower precedence than and. But when I type in idle this:

>>> True and True or False
True
>>> True and False or True
True
>>> True and False
False

Why is the result of this True and False or True expression True?

Upvotes: 0

Views: 1944

Answers (4)

En-code
En-code

Reputation: 49

You statement is asking to do the following

First python evaluates the expression on the left;

Evaluation 1: True and false (Since this evaluates to false python then looks to the or expression)

Evaluation 2: True or false

Which then evaluates to true

You may also want to take a look at Boolean logic and truth tables to assist with understanding how this works.

Upvotes: 1

Mariy
Mariy

Reputation: 5924

Highest precedence means where you will put the parentheses

((True and True) or False)  # True
((True and False) or True)  # True
(True and False)            # False

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599796

In fact, operator precedence has nothing to do with this result; it would be the same wherever you put the parentheses, since or always returns True if either of its arguments are true. So:

True and (False or True) == True and (True) == True
(True and False) or True == (False) or True == True

Upvotes: 1

Mureinik
Mureinik

Reputation: 311883

Higher precedence means that an operator would be evaluated before an operator with lower precedence, like, e.g., in arithmetic, multiplication should evaluated before addition, so 1 + 2 * 3 will result in 7 and not 9.

In your usecase, True and False is evaluated first, giving False. This result is then evaluated with the or operator (i.e., False or True), resulting in True.

Upvotes: 2

Related Questions