Logical operator binding of AND and OR in Python
<p>Yesterday while constructing a conditional statement I ran into what seems to me to be a strange precedence rule. The statement I had was</p>

<pre><code>if not condition_1 or not condition_2 and not condition_3:
</code></pre>

<p>I found that</p>

<pre><code>if True or True and False:
    # Evaluates to true and enters conditional
</code></pre>

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

<pre><code>if (True or True) and (False):
</code></pre>

<p>But in actual fact it is </p>

<pre><code>if (True) or (True and False):
</code></pre>

<p>Which seems odd to me? </p>

<p>From python wiki :</p>

<blockquote>
  <p>The expression <a href="https://docs.python.org/2/reference/expressions.html#and" rel="nofollow"><strong>x and y</strong></a> first evaluates x; if x is false, its <strong>value</strong> is returned; otherwise, y is evaluated and the resulting <strong>value</strong> is returned.</p>
  
  <p>The expression <strong>x or y</strong> first evaluates x; if x is true, its <strong>value</strong> is returned; otherwise, y is evaluated and the resulting <strong>value</strong> is returned.</p>
</blockquote>

<p>So in your case</p>

<pre><code>if True or True and False:
</code></pre>

<p>Since interpreter encounters <code>True</code> before <code>or</code> it doesn't continue to <code>and</code> expression and evaluates to <code>True</code></p>

python logical-operators