Boolean
Python has two boolean literals: True and False (capitalised). Booleans represent the result of logical comparisons and are used extensively in conditions....
Boolean Basics
Python has two boolean literals: True and False (capitalised). Booleans represent the result of logical comparisons and are used extensively in conditions. Because bool is a subclass of int, True behaves as 1 and False as 0 in arithmetic. For example, True + True gives 2, and sum([True, False, True, True]) gives 3. This feature lets you count truthy values in a list using sum() and a generator expression.
Truthiness and Falsiness
Every Python object has a boolean interpretation. Objects considered False (falsy): None, False, 0, 0.0, 0j, empty string "", empty list [], empty tuple (), empty dict {}, empty set set(). Everything else is considered True (truthy). You can check an object's boolean value with bool(x). This is why if my_list: is valid Python for checking if a list is non-empty — it is idiomatic and preferred over if len(my_list) > 0:.
Short-Circuit Evaluation
Python evaluates and and or expressions with short-circuit logic. For and, if the left operand is falsy, Python returns it immediately without evaluating the right side. For or, if the left operand is truthy, Python returns it without evaluating the right. Importantly, these operators return one of their operands, not necessarily True or False. Example: 0 or "default" returns "default"; "value" and "other" returns "other". This idiom is commonly used for default values.
Boolean in Practice
Booleans are used in conditions (if x > 0:), while loop guards (while keep_running:), list comprehension filters ([ x for x in items if x]), and as flags. A common pattern to count items meeting a condition: count = sum(1 for x in data if x > 0). Since True == 1, you can also write: count = sum(x > 0 for x in data). This concise idiom leverages the int nature of bool.
Comparison Results
All comparison operators (==, !=, <, >, <=, >=, in, not in, is, is not) return boolean values. Python allows chaining comparisons naturally: 0 < x <= 100 is equivalent to x > 0 and x <= 100 but more readable. The not operator inverts a boolean: not True gives False. not can also be applied to any object: not [] gives True because [] is falsy. Remember that not is a lower precedence than comparison operators.
Exam Tip
Exams exploit the int nature of bool. Question: what does True == 1 return? True. What does True is 1 return? False — they are equal in value but not the same object. What does bool("False") return? True — because any non-empty string is truthy, including the string "False". Students often assume bool("False") would be False, but only the empty string "" is falsy. This is a classic trick question in Python assessments.