Basics
Booleans
Use booleans for facts that are either true or false. Python spells the constants True and False.
Use and, or, and not to combine truth values. These operators read like English and short-circuit when possible.
Source
logged_in = True
has_permission = False
print(logged_in and has_permission)
print(logged_in or has_permission)
print(not has_permission)Output
False
True
TrueComparisons produce booleans too, so they compose naturally with logical operators in conditions and validation checks.
Source
name = "Ada"
print(name == "Ada" and len(name) > 0)Output
Truebool is a subclass of int, which is occasionally a footgun. True behaves as 1 and False as 0 in arithmetic, and isinstance(True, int) is True. When a function must reject booleans, exclude them explicitly with isinstance(value, int) and not isinstance(value, bool).
Source
print(isinstance(True, int))
print(True + True)
print(sum([True, True, False, True]))
def is_strict_int(value):
return isinstance(value, int) and not isinstance(value, bool)
print(is_strict_int(True))
print(is_strict_int(1))Output
True
2
3
False
TrueNotes
- Boolean constants are
TrueandFalse, with capital letters. andandorshort-circuit: Python does not evaluate the right side if the left side already determines the result.- Prefer truthiness for containers and explicit comparisons when the exact boolean condition matters.
boolsubclassesint;isinstance(True, int)isTrue. Exclude booleans explicitly when only "real" integers should pass.
See also
- related: Truthiness
- related: Operators
- next depth: Conditionals
Run the complete example
Expected output
False
True
True
True
True
2
3
False
True
Execution time appears here after you run the example.