Programming Search⌘K

Featureintro

Boolean operators

Also called Python and or not, logical operators, short-circuit evaluation, truthiness, truth value testing.

Python's Boolean operators are the keywords and, or and not. and and or short-circuit and return one of their operands, not always a bool; not always returns True or False.

Language
Python

Synopsis

age, member = 25, False
print(age >= 18 and not member, age < 13 or member, not age)
print(0 or "default", "x" and "y", [] and 1 / 0)
Output
True False False
default y []

Semantics

r1. In a Boolean operation or a control flow condition, False, None, numeric zero of all types, and empty strings and containers are false, and all other values are true. A class can set the truth value of its objects with __bool__().1 Without __bool__(), a __len__() that returns zero also makes an object false.2 Example: truthiness.

r2. x and y first evaluates x; if x is false, its value is returned; otherwise y is evaluated and its value is returned. x or y returns x if it is true, and otherwise evaluates and returns y.1 Example: short-circuit.

r3. "Note that neither" and nor or restricts the result to False and True: each returns the last evaluated argument. "Because" not "has to create a new value, it returns a boolean value regardless of the type of its argument".1 Example: bool-ops.

r4. The arguments are evaluated from left to right, "and evaluation stops as soon as the outcome is determined". Among the three, not has the highest priority and or the lowest, so A and not B or C is (A and (not B)) or C. All three bind looser than the comparisons.3 Example: bool-precedence.

r5. Because not has a lower priority than the non-Boolean operators, not a == b is read as not (a == b), and a == not b is a syntax error.4 Example: bool-precedence.

Examples

Short-circuit evaluation (rules r2 and r4): the calls stop as soon as the result is known.

def check(name, result):
    print("check", name)
    return result

print(check("a", True) and check("b", False) and check("c", True))
print(check("a", False) or check("b", 0) or check("c", "found"))
Output
check a
check b
False
check a
check b
check c
found

The false values of rule r1. A non-empty string or list is true even when it holds a zero.

values = [None, False, 0, 0.0, 0j, "", (), [], {}, set(), range(0), "0", [0], " "]
print([bool(v) for v in values])
Output
[False, False, False, False, False, False, False, False, False, False, False, True, True, True]

A class with __len__() gets its truth value from its length (rule r1).

class Box:
    def __init__(self, items):
        self.items = items

    def __len__(self):
        return len(self.items)

print(bool(Box([])), bool(Box([1])), Box([]) or "empty")
Output
False True empty

Priorities (rules r4 and r5).

A, B, C = False, False, True
print(A and not B or C, (A and (not B)) or C, A and (not B or C))
print(not 1 == 2, not (1 == 2))
Output
True True False
True True

Pitfalls

x == a or b is always true

or binds looser than == (rule r4), so color == "red" or "green" is (color == "red") or "green", and a non-empty string is true.

This code runs but gives a wrong answer on purpose.

color = "blue"
if color == "red" or "green":
    print("warm")
print(color == "red" or "green")
print(color in ("red", "green"))
Output
warm
green
False

Use in with a tuple, or repeat the comparison.

or replaces every false value

value or default also replaces 0, an empty string and [], not only None (rules r1 and r2). PEP 8 warns: "beware of writing if x when you really mean if x is not None".5

This code runs but gives a wrong answer on purpose.

def scale(value, factor=None):
    factor = factor or 10
    return value * factor

print(scale(3), scale(3, 2), scale(3, 0))
Output
30 6 30

Write factor = 10 if factor is None else factor to keep a 0.

&& and || are not Python

The Boolean operators are keywords. && is a syntax error, and & and | are bitwise operators that do not short-circuit.

This code raises SyntaxError, on purpose.

ready, valid = True, False
print(ready && valid)

Comparison

Go's &&, || and ! "apply to boolean values and yield a result of the same type as the operands", and the right operand is evaluated only if needed.6 Python's and and or short-circuit the same way, but accept operands of any type and return one of them (rule r3), so "" or "guest" is "guest"; in Go that expression does not compile.

References

  1. The Python Language Reference, Python 3.15, 6.11 Boolean operations
  2. Built-in Types, Python 3.15 documentation, Truth Value Testing
  3. The Python Tutorial, Python 3.15, 5.7 More on Conditions
  4. Built-in Types, Python 3.15 documentation, Boolean Operations, and, or, not
  5. PEP 8: Style Guide for Python Code, Programming Recommendations
  6. The Go Programming Language Specification, Logical operators

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source