Boolean Logic in Python: and, or, not, and short-circuiting
Real conditions are rarely a single test. and, or, and not compose booleans into the exact rule you want — like fire only if you can shoot and the game isn't paused.
The big idea
and is True only when both sides are; or is True when either is; not flips a boolean — and Python stops evaluating as soon as the answer is settled.
See it in code
Three operators combine booleans: and needs both sides true, or needs either, and not flips one:
print(True and False)
print(True or False)
print(not True)False True False
True and False is False, True or False is True, and not True is False. Everything else is these three, composed.
The real power is folding a comparison into the expression. ammo > 0 is a boolean, so it slots straight into an and:
can_shoot = True
ammo = 3
print(can_shoot and ammo > 0)True
can_shoot is true and ammo > 0 is true, so the whole thing is True. Drop ammo to 0 and that side flips — sinking the and.
Now three gate checks a shooter makes at once. can_shoot and not paused allows a shot only when both hold; the second line needs ammo > 0, and with zero ammo it's False; or is satisfied by either side:
can_shoot = True
paused = False
ammo = 0
print(can_shoot and not paused)
print(can_shoot and ammo > 0)
print(paused or ammo > 0)True False False
and needs everything True; a single False sinks it. Python also short-circuits: in ammo > 0 and risky(), if ammo > 0 is already False, it never calls risky(). That lets you guard a risky check behind a cheap one.
Composed booleans are the grammar of every rule engine: allow a login if verified and not locked, keep a particle if on_screen and alive, trigger a trade if price > avg or volume_spike. Short-circuiting — putting the cheap or protective test first — is both a speed and a safety trick.
Try it yourself
Predict not (can_shoot and paused) before running it. Then reorder a guard like data and data[0] == 'A' — putting data first prevents an index error when the list is empty, thanks to short-circuiting.
The common mistake
Chaining comparisons the wrong way, or forgetting precedence. not binds tighter than and, which binds tighter than or, so a or b and c means a or (b and c). When in doubt, add parentheses to say exactly what you mean.
What it unlocks
Composed conditions drive conditionals and loop guards, and rest on the booleans produced by comparison operators.