Skip to content
Tactiverge

Python reference

Comparisons and Boolean expressions

Also called: and · or · not · True False · short-circuit · chained comparison

Definition

Comparisons such as a < b give True or False; and, or and not combine them. Python allows chained comparisons like 0 <= x < 10.

Picture it

and needs both sides true; or needs at least one. Python stops as soon as it knows the answer (short-circuit), so x != 0 and 10 / x > 2 never divides by zero. These are the same rules as AND, OR and NOT gates.

Worked example

With x = 7, evaluate 0 <= x < 10, x > 5 and x % 2 == 0, and not (x > 5 or x < 0).

  1. 0 <= 7 < 10 → True
  2. 7 > 5 is True, 7 % 2 == 0 is False → False
  3. x > 5 is True, so the or is True, not gives False

AnswerTrue, False, False.

Common misconceptions

  • Misconception: Empty lists, 0 and "" count as False in an if; that is convenient but can hide bugs when 0 is a valid reading.
  • Misconception: Use == to compare values and is only for None.