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>As you said <code>and</code> has a higher preference, so your expression with parenthesis will be exactly what you said:</p>

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

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

python logical-operators