Python Booleans: Comparisons, and, or, not
Programs make decisions, and decisions need yes-or-no answers. Python's bool type has exactly two values, True and False, both capitalized. You rarely type them directly; they usually come from comparisons.
Comparison operators
== (equal), != (not equal), <, <=, > and >= compare two values and return a bool. Python lets you chain them the way you would write maths: 1 < age < 30 means 1 < age and age < 30. Text compares alphabetically by character code, so "apple" < "banana" is True but uppercase letters sort before lowercase ones.
Use is only to check identity, mainly x is None. For comparing values, always use ==.
Combining conditions
a and bis true only when both sides are true.a or bis true when at least one side is true.not aflips the value.
Both and and or short-circuit: Python stops evaluating as soon as the answer is known. In user and user.is_admin, the second part never runs if user is empty. not binds tighter than and, which binds tighter than or; add parentheses when mixing them.
Expected output
True False True True True False False True False False
Truthy and falsy values
Any value can be used where a bool is expected. Empty or zero values are falsy: 0, 0.0, "", [], {}, set() and None. Nearly everything else is truthy, including the string "0" and the list [0], because they are not empty. That is why if items: is the idiomatic way to ask "does this list have anything in it?". The built-in bool() shows how a value would be judged.
The final line of the example repeats a lesson from the numbers chapter: floating-point results are approximations, so test them with math.isclose() instead of ==.
Common mistakes
- Writing
=instead of==in a condition, which is a syntax error insideif. - Writing
truein lowercase; it raisesNameError. - Testing
if x == True:instead of the simplerif x:. - Writing
if color == "red" or "blue":. The right side is the non-empty string"blue", which is always truthy. Writecolor in ("red", "blue").
Summary
TrueandFalsecome from comparisons such as==and<.and,orandnotcombine conditions and short-circuit.- Empty and zero values are falsy; most other values are truthy.
Quiz: Booleans and logic