0

I don't understand why the first one is true, does it short circuit when it sees True or?

>>> True or False and False
True
>>> True or False and True
True
1
  • Also this and this and many more. Commented Feb 3, 2019 at 8:26

2 Answers 2

3

In Python, and has a higher precedence than or, meaning that and will bind first (search for Operator precedence in the following section of the Python documentation, for example(1)).

Hence your two statements are equivalent to (despite your incorrect assertion that Python reads left to right):

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

And, regardless of what the result of the parenthesised sub-expression in those two expressions above, oring that with True will give True.


(1) The relevant parts of that link (the explanatory text and the initial part of the table) are included below for completeness, with my emphasis:

The following table summarizes the operator precedence in Python, from lowest precedence (least binding) to highest precedence (most binding). Operators in the same box have the same precedence. Unless the syntax is explicitly given, operators are binary. Operators in the same box group left to right (except for exponentiation, which groups from right to left).

Operator Description
-------- -----------
lambda Lambda expression
if – else Conditional expression
or Boolean OR
and Boolean AND
not x Boolean NOT

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

Comments

2

Thanks to PM 2Ring's comment: and has higher precedence than or. So Python will execute and first, so The first one is like this:

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

result of (False and False) is False and True or False is True.

The second one is like this:

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

result of (False and True) is again False and True or False is True.

1 Comment

You should mention that and has higher precedence than or, similar to * having higher precedence than +.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.