Skip to content

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.


Python uses plain English keywords for its logical operators, which makes code more readable but requires a precise understanding of their “Truth Tables.”

Returns True only if both sides are True. If the first side is False, the whole thing is False.

Returns True if at least one side is True. If the first side is True, the whole thing is True.

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.

  • For A and B: If A is False, Python returns A and completely ignores B. It doesn’t even look at it.
  • For A or B: If A is True, Python returns A and completely ignores B.
short_circuit_guard.py
# 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")

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:

  1. not (A and B) is the same as (not A) or (not B)
  2. not (A or B) is the same as (not A) and (not B)
simplification.py
# 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:

  1. Comparisons (==, >, etc.)
  2. not
  3. and
  4. or
precedence_trap.py
# Evaluated as: True or (False and False) -> True or False -> True
result = True or False and False

Always 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!


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?”
identity_demo.py
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True (Same content)
print(a is b) # False (Different objects in memory)