In python, short circuiting is supported by various boolean operators and functions. Short-circuit evaluation means that when evaluating Boolean expression like AND and OR, we can stop as soon as we find the first condition which satisfies or negates the expression.
By short circuiting we mean the stoppage of execution of boolean operation if the truth value of expression has been determined already. The evaluation of expression takes place from left to right.
Short Circuiting in Boolean Operators:
The chart given below gives the short circuiting of in case of boolean expressions:
|a or b||If a is false, then b else a||Only evaluates the second argument (b) if the first one (a) is false.|
|a and b||If a is false, then a else b||Only evaluates the second argument (b) if the first one (a) is true.|
|not a||If a is false, then True, else False||Not has a lower priority than non-boolean operators.|
Incase of an or expression, the python interpreter first takes the first statement and check to see if is true. When the first statement is true, then python returns that object’s value without looking into the second argument. This is because for an or expression, the whole thing is true if one of the values is true; and the program doesn’t look into second statement. However, if the first object value evaluates to false, python checks the second statement and returns that value. The second half determines the truth value of the expression since the first half was false. This process of interpreter is called “short-circuiting”. It is a common way of evaluating Boolean expression in many programming languages.
Similarly, for an and expression, python uses a short circuit technique to speed truth value evaluation. If the first statement is false then the whole thing must be false and it returns that object value (false) else, if the first value is true it checks the second and returns that value.
def func_1(): a = 3 b = 5 c = 7 print((a<b) and (b<c)) print((a<b) or (b<c)) func_1()