Also known as: bool
The bool type in Python has exactly two instances: True and False. Booleans are the result of comparison operators (==, !=, <, >, <=, >=), membership tests (in, not in), and identity checks (is, is not). They are the primary currency of control flow: if, while, and assert all evaluate boolean conditions.
A surprising fact about Python's booleans is that bool is a subclass of int: True has integer value 1 and False has integer value 0. This means you can use booleans in arithmetic — True + True evaluates to 2 — and you can sum a list of booleans to count how many are true. This design decision dates back to Python's pre-boolean era when 0 and 1 served as the only truth values.
Python has a rich notion of truthiness: every object can be evaluated in a boolean context. By default, objects are truthy. The "falsy" values are None, False, zero in any numeric type (0, 0.0, 0j), and any empty collection ('', [], (), {}, set(), frozenset()). Custom classes can define __bool__() or __len__() to control their truthiness. The logical operators and, or, and not work with truthiness, and and/or short-circuit: they return the determining operand rather than converting to True or False.
Discussed in:
- Chapter 3: Variables and Data Types — Booleans