< previous | Table of Contents | next > |
3.5 SHORT-CIRCUIT EVALUATION
Expressions in Python are evaluated from left to right. Short-circuit evaluation refers to the process where the second argument of a logical expression is evaluated only if the first argument does not suffice to determine the value of the expression. This concept is particularly relevant when using the logical operators and
and or
. This is something to note about how the Python interpreter works when evaluating expressions.
and
can only be True
if both operands are True
. If the first part of the expression is False
, the entire expression must be False
, and the second operand does not need to be evaluated.
or
operator is True
, and at least one of the conditions is True
. If the first operand is True
, the whole expression must be True
. If the first operand is False
, only then would the subsequent operands need to be evaluated to determine the final value for the expression.
Take the following as an example:
x = 0.7 y = 12 if x > 0 or y == 0: print("At least one of the operands was True!")
In this example, the if
statement condition would be evaluated to have the truth value of True
if the value of x
is greater than 0. Given that the or
expression evaluates to True
if at least one of the conditions is True
, there is no need to assess whether y
is equal to zero. Notice also how we check equality in the if
condition using ==
, not =
.
KEY THINGS TO REMEMBER
- Short-circuit evaluation is a feature of Python where the second argument of an expression is evaluated only if it needs to be evaluated to find the final result of a logical expression.
- In the case of
and
, if the left side of the expression evaluates toFalse
, then the whole expression must beFalse
, and there is no need to evaluate the right side. - In the case of
or
, if the left side of the expression evaluates toTrue
, then the whole expression must beTrue
, and there is no need to evaluate the right side.
< previous | Table of Contents | next > |