Chapter 2 · Apprentice

Boolean logic: and / or / not

Booleans combine with three keywords:

  • and — true only if both sides are true.
  • or — true if either side is true.
  • not — flips a bool (not True is False).

These let one condition express a compound rule: "the door opens only if the name is right and the code is right."

Two important behaviours. Short-circuiting: and stops at the first falsy value, or stops at the first truthy one — the rest isn't even evaluated. And Python lets you chain comparisons naturally: 0 <= x <= 100 means 0 <= x and x <= 100.

Syntax

a and b    # both must be true
a or b     # at least one true
not a      # flip

name == "sam" and code == "1234"
0 <= score <= 100        # chained comparison

Worked examples

Both conditions must hold

def can_enter(name, code):
    return name == "sam" and code == "1234"

print(can_enter("sam", "1234"))   # True
print(can_enter("sam", "0000"))   # False
print(can_enter("eve", "1234"))   # False

or for fallbacks, not for negation

is_admin = False
is_owner = True
if is_admin or is_owner:
    print("can edit")      # runs — one side is True

if not is_admin:
    print("not an admin")  # runs

Short-circuiting avoids the crash on the right

items = []
# `items` is falsy, so the right side is never evaluated:
if items and items[0] == "x":
    print("first is x")
else:
    print("empty or not x")   # safe — no IndexError

Common mistakes & gotchas

and/or return a value, not always a bool

"" or "default" returns "default" (the first truthy operand), and 5 and 0 returns 0. Handy for defaults, but don't assume the result is literally True/False — it's one of the operands.

Writing "if x == True"

If x is already a bool, just write if x: (and if not x:). Comparing to True/False is redundant and == True even breaks for truthy-but-not-True values.

Precedence: not > and > or

not binds tightest, then and, then or. a or b and c means a or (b and c). When in doubt, add brackets to make intent obvious.

Why it matters

Real rules are rarely a single check — access control, validation, and business logic all combine conditions. Getting and/or/not right (and understanding short-circuiting) is the difference between a rule that's correct and one that's nearly correct.