How are conditional statements with multiple conditions evaluated?
<p>I'd expect the following two code blocks to be evaluated the same way, but it would seem that is not the case.</p>

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

<p>True is printed</p>

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

<p>False is printed           </p>

<p>Here's my breakdown of the logic:</p>

<p>True or False => True</p>

<p>True and False => False</p>

<p>By substitution, (True or False) and False => True and False => False                                                                                                  </p>

<p>Why does this happen? </p>

<p>This is because of <a href="https://docs.python.org/2.7/reference/expressions.html#operator-precedence" rel="nofollow">operator precedence</a>. Per the Python 2.x and 3.x docs, the <code>and</code> operator has higher precedence than the <code>or</code> operator. Also, have a look at the boolean truth table:</p>

<p><a href="http://i.stack.imgur.com/nl0W8.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/nl0W8.jpg" alt="enter image description here"></a></p>

<p>That means in your expression:</p>

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

<p>In the expression, <code>False and False</code> is grouped together because of precedence. That means Python evaluates it as:</p>

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

<p>Now, it's evaluated left to right. Since the first condition is <code>True</code>, it short-circuits and skips the second condition and evaluates to <code>True</code> printing 'True'. (This short-circuits because if the first side is true, it <em>has to be true</em>.)</p>

<p>Now in your second example:</p>

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

<p>This makes <code>True or False</code> evaluate first, which gives <code>True</code>. Then it does <code>True and False</code> which is <code>False</code>, printing 'False'.</p>

<pre><code>&gt;&gt;&gt; print(True or False)
True
&gt;&gt;&gt; print(True and False)
False
</code></pre>

python