CP104: Notes - Short Circuit Evaluations

Python handles Boolean conditions using and and or in a special way. If the first Boolean expression of a two-part condition using an and evaluates to False, then the second condition is not evaluated. In the following example:

    
if x > 0 and y < 0:
    ...

  

if x is less than 0 then the entire condition evaluates to False (for and both conditions must be True for the entire expression to be True), and the second condition involving y is not evaluated at all.

With or it is the opposite. In the following example:

    
if x > 0 or y < 0:

  

if x is greater than 0 then the entire condition evaluates to True ( for or only one condition must be True for the entire expression to be True), and the second condition is not evaluated at all.

This short-circuiting of Boolean expressions is often not significant, but the order in which conditions are evaluated can cause problems. Think carefully about which conditions should be checked first.