Python Booleans

Tutorial 8 of 65 · pythondeck.com Python course

bool is a subclass of int: True equals 1, False equals 0. Any object can be tested for truth value; empty containers, zeros and None are falsy. Boolean operators and, or and not short-circuit and return one of the original operands.

Booleans represent logical true and false. They drive conditional execution, filtering, and flags in configuration. Python's bool is a subclass of int with values True == 1 and False == 0, but you should treat them as logic, not counters.

Truthy and falsy rules let you write concise conditions, but implicit conversion can hide bugs when empty strings or zero are valid data.

Only two constants: True and False (capitalized).

Boolean operators: and, or, not with short-circuit evaluation.

Comparisons chain: a < b < c; membership: x in container.

Truthy: non-zero numbers, non-empty containers, non-None objects; falsy: 0, "", [], None.

bool(x) constructs explicit booleans from any object.

Identity tests: is, is not for None and singleton checks.

and/or return the last evaluated operand, not strictly bool—useful for defaults like name or "anonymous" but surprising if you expect always True/False.

Do not write if flag == True; use if flag: or if not flag:.

Bitmasking uses int operators (&, |); booleans are for control flow. Use explicit bool() when APIs return 0/1 integers you must normalize.

Using if x == None instead of if x is None.

Treating empty list as missing when [] is valid data—be explicit.

Relying on if len(items): when if items: is clearer (unless NumPy array).

Comparing booleans to integers unnecessarily in conditions.

Make conditions express intent: if user is not None rather than double negatives.

Return booleans directly: return x > 0 instead of if x > 0: return True else: return False.

Use any() and all() over manual loops for predicates on collections.

Name flags positively (is_enabled) to avoid confusing if not is_disabled.

Write if items: for non-empty sequences unless zero is meaningful data you must handle separately.

Re-read the examples below with these ideas in mind; change variable names and inputs to match your own project.

The program below demonstrates truthiness. Read the comments on each line, run the code, then change names or values to see how the output shifts.

# Example: Truthiness
# Run in the REPL or save as a .py file and execute with python.
for v in [0, 1, "", "x", [], [1], None]:
    print(bool(v), v)

This sample walks through short-circuit in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.

# Example: Short-circuit
# Run in the REPL or save as a .py file and execute with python.
x = 0
print(x or "default")    # 'default'
print(x and 1/x)         # 0, avoids division

Here is a hands-on illustration of compare. Follow the inline comments first; only then execute the snippet and compare the result with what you expected.

# Example: Compare
# Run in the REPL or save as a .py file and execute with python.
print(3 < 5 < 9)   # chained comparison
print(not (1 == 2))

The program below demonstrates truthiness rules. Read the comments on each line, run the code, then change names or values to see how the output shifts.

# Empty containers and zero are falsy; most other values truthy
candidates = [0, 1, "", "x", [], [1], None, {}, {"k": 1}]
for value in candidates:  # iterate test values
    flag = bool(value)  # explicit conversion to True/False
    print(repr(value), "->", flag)  # see mapping
print(3 > 2 and 2 > 1)  # and short-circuits on first False
print(3 > 5 or 1 < 2)  # or stops at first True
print(not False)  # unary not flips boolean
print(bool("False"))  # non-empty string is True (common pitfall)

This sample walks through chained comparisons in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.

# Python allows mathematic-style chained comparisons
x = 15  # middle value
print(10 < x < 20)  # equivalent to 10 < x and x < 20
print(0 <= x <= 10)  # False because x exceeds 10
a = b = 7  # equal ints
print(a == b, a is b)  # True True for small cached ints
values = [1, 2, 2, 3]  # list with duplicate
print(values.count(2) > 0)  # membership via count
print(2 in values)  # preferred membership test
print(all(v > 0 for v in values))  # True if every element > 0
print(any(v > 3 for v in values))  # True if any element > 3

« Python Strings All tutorials Python Operators »