Logical Expression and Short-Circuit Evaluation

Explore the logical operators in Python and their use as short-circuit evaluators.

Logical expressions

We can create a compound expression by combining logical operations. De Morgan’s laws are based on this paradigm. Consider the following expression:

not(a or b)

The compound expression above is true or false depending on different combinations. If a and b are false, the negation of subexpression (a or b) is true. If any one of them is true, then the value will be false, and this combination might take different shapes according to the truth table.

A major part of discrete mathematical operations is based on Boolean algebra and the associated logical expressions. To recap, we need to remember that there are three basic logical operators. The following symbols/operators are used in Python and other languages:

  • Conjunction: and in Python; && in Java, C++, C, Dart, and PHP
  • Disjunction: or in Python; || in Java, C++, C, Dart, and PHP
  • Negation: not in Python; ! in Java, C++, C, Dart, and PHP

Logical operators manipulate the logical values. In the same way, relational operators also manipulate the logical values. There are two kinds of relational operators: equality and order.

The two equality operators are:

  • ==
  • !=

The == operation is true when the two operands have the same value. In the same way, the != operation is true when two operands have different values.

The ordering operators test the relative size of two values. They are:

  • < (less than)
  • > (greater than)
  • >= (greater than or equal to)
  • <= (less than or equal to)

Get hands-on with 1400+ tech skills courses.