Boolean Logic & Evaluation
Logic is the nervous system of your code. While a single if statement is simple, complex applications require combining many conditions into a coherent decision.
In this chapter, we move beyond basic comparisons to explore the formal logic that governs how Python evaluates complex expressions.
1. The Trinity of Logic: and, or, not
Section titled “1. The Trinity of Logic: and, or, not”Python uses plain English keywords for its logical operators, which makes code more readable but requires a precise understanding of their “Truth Tables.”
and (Logical Conjunction)
Section titled “and (Logical Conjunction)”Returns True only if both sides are True. If the first side is False, the whole thing is False.
or (Logical Disjunction)
Section titled “or (Logical Disjunction)”Returns True if at least one side is True. If the first side is True, the whole thing is True.
not (Logical Negation)
Section titled “not (Logical Negation)”Inverts the value. It has a very high precedence, often requiring parentheses for clarity.
2. Under the Hood: Short-Circuiting (The Efficiency Secret)
Section titled “2. Under the Hood: Short-Circuiting (The Efficiency Secret)”Python does not evaluate logic like a math equation where you solve everything and then decide. It evaluates from left to right and stops as soon as it is mathematically certain of the result.
How it Works:
Section titled “How it Works:”- For
A and B: IfAis False, Python returnsAand completely ignoresB. It doesn’t even look at it. - For
A or B: IfAis True, Python returnsAand completely ignoresB.
# This would normally crash if 'user' was None (None.is_admin)# But because of short-circuiting, if 'user' is None,# Python stops and never tries to access '.is_admin'.if user is not None and user.is_admin: print("Welcome, Admin")3. De Morgan’s Laws
Section titled “3. De Morgan’s Laws”When you need to negate a complex condition, you can’t just put not in front and expect it to be easy to read. De Morgan’s Laws help you simplify code:
not (A and B)is the same as(not A) or (not B)not (A or B)is the same as(not A) and (not B)
# Hard to read:if not (is_weekend and is_sunny): print("Staying in.")
# Easier to read (De Morgan's):if not is_weekend or not is_sunny: print("Staying in.")4. Operator Precedence (The PE(N)DAS of Logic)
Section titled “4. Operator Precedence (The PE(N)DAS of Logic)”When you combine multiple operators, they are evaluated in this order:
- Comparisons (
==,>, etc.) notandor
# Evaluated as: True or (False and False) -> True or False -> Trueresult = True or False and FalseAlways use parentheses to avoid bugs and make your code readable for others. (True or False) and False results in False, which is a completely different outcome!
5. Identity (is) vs. Equality (==)
Section titled “5. Identity (is) vs. Equality (==)”A common source of bugs is using is when you mean ==.
==(Value Equality): Calls the__eq__method. It asks: “Do these two objects contain the same data?”is(Identity Equality): Compares memory addresses. It asks: “Are these two variables pointing to the exact same physical object in RAM?”
a = [1, 2, 3]b = [1, 2, 3]
print(a == b) # True (Same content)print(a is b) # False (Different objects in memory)