1

Yesterday while constructing a conditional statement I ran into what seems to me to be a strange precedence rule. The statement I had was

if not condition_1 or not condition_2 and not condition_3:

I found that

if True or True and False:
    # Evaluates to true and enters conditional

In my mind (and from previous experience in other languages) the and condition should have precedence as the statement is evaluated - so the statement should be equivalent to

if (True or True) and (False):

But in actual fact it is

if (True) or (True and False):

Which seems odd to me?

2

2 Answers 2

1

From python wiki :

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

So in your case

if True or True and False:

Since interpreter encounters True before or it doesn't continue to and expression and evaluates to True

Sign up to request clarification or add additional context in comments.

Comments

0

As you said and has a higher preference, so your expression with parenthesis will be exactly what you said:

if (True) or (True and False)

Since True or (anything) will be True regardless anything here, the result will be True. Even if anything would be evaluated, which is not in a shortcut evaluation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.