3.6 Short-Circuit Evaluation

Short-circuit evaluation is a technique used in programming to improve efficiency when evaluating compound Boolean expressions (expressions that combine two or more Boolean values using logical operators such as and or or).

Instead of always evaluating all parts of the expression, the program stops as soon as it can determine the final result.

This is particularly useful when later expressions might be unnecessary or even potentially error-prone (e.g., division by zero, accessing invalid indexes, etc.).

Short-circuiting is automatically performed by the logical operators and and or.

'or' operator

If the left operand is True, the compound expression is definitely True, and there is no need to evaluate the right operand.

'and' operator

If the left operand is False, the compound expression is definitely False, and the right operand is not evaluated.

Practical Use Cases

  • User Input Handling
    • Reading user input as a string for initial processing.
  • Numeric Conversion
    • Converting string-formatted numbers for calculations.
  • Output Formatting
    • Using str() to format numbers as strings for display.