Skip to content

Module 5 · Conditional Statements — topic 7 of 10

Logical expressions

Read, evaluate and simplify logical expressions: truth tables, short-circuit evaluation, De Morgan’s laws, and how and/or return operand values rather than plain Booleans.

Intermediate 12 min read·Lesson 66 of 306 in Python Programming

Learning objectives

  • Evaluate logical expressions step by step
  • Simplify negations with De Morgan’s laws
  • Use short-circuiting safely

Definition

Read, evaluate and simplify logical expressions: truth tables, short-circuit evaluation, De Morgan’s laws, and how and/or return operand values rather than plain Booleans.

Introduction

A logical expression is any expression built from conditions and the operators and, or and not. Being able to evaluate one in your head, and rewrite it into a simpler equivalent, is a core reasoning skill for programming.

Why it matters

Conditions in real programs grow over time. A condition that is hard to read is easy to break when someone changes it. Simplifying logical expressions makes them trustworthy, and understanding short-circuiting lets you guard against errors such as reading from an empty list.

Detailed explanation

Evaluate inside parentheses first, then not, then and, then or.

Short-circuiting: in a and b, if a is false then b is never evaluated; in a or b, if a is true then b is never evaluated. Put guards on the left: user is not None and user.is_active.

and and or return one of their operands: x or default gives x when x is truthy, otherwise default. x and y gives x if x is falsy, otherwise y. Only not always returns True or False.

De Morgan’s laws: 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). Use them to push not inward and remove double negatives.

Double negation: not not x is simply bool(x). Conditions such as if not is_invalid: read better as if is_valid:.

Equivalent expressions can be checked by trying every combination of True and False, which is exactly what a truth table does.

Syntax

Text
not (a and b) == (not a) or (not b)
not (a or b) == (not a) and (not b)
  • Moving not inside swaps and with or.
  • Each part is negated individually.
  • Both sides give the same result for every combination.

Code examples

Operand return values

Python
nickname = ""
print(nickname or "Anonymous")
print(0 and "unused")
print([1] and "has items")
Output
Anonymous
0
has items

Short-circuit protects

Python
scores = []
print(len(scores) > 0 and scores[0] > 50)
Output
False

scores[0] is never evaluated, so no IndexError occurs.

More examples

Checking De Morgan’s laws with a truth table

Python
from itertools import product
print("a b not(a and b) (not a) or (not b)")
for a, b in product([True, False], repeat=2):
left = not (a and b)
right = (not a) or (not b)
print(f"{a!s:<5} {b!s:<5} {left!s:<13} {right!s:<5}")
all_match = all(
(not (a or b)) == ((not a) and (not b))
for a, b in product([True, False], repeat=2)
)
print("Second law holds:", all_match)
Output
a     b     not(a and b)  (not a) or (not b)
True  True  False         False
True  False True          True
False True  True          True
False False True          True
Second law holds: True

Step-by-step explanation

  • product([True, False], repeat=2) generates all four combinations of a and b.
  • For each pair, both sides of the first law are computed and printed side by side.
  • {a!s:<5} converts the Boolean to text and pads it to five characters so columns align.
  • all(...) checks the second law for every combination and confirms it holds.

Expected output

Running “Checking De Morgan’s laws with a truth table” prints exactly:

TextOutput
a b not(a and b) (not a) or (not b)
True True False False
True False True True
False True True True
False False True True
Second law holds: True

Practical applications

  • Search engines and database queries combine filters with AND, OR and NOT.
  • Configuration loaders use value or default to fill in missing settings.
  • Security checks put cheap, safe tests first to benefit from short-circuiting.

Best practices

  • Push not inward with De Morgan’s laws to simplify.
  • Put guard checks on the left of and.
  • Use value or default only when falsy values aren’t valid input.

Common mistakes

Negating only part of a compound condition

Avoid

not a and b # meant not (a and b)

Prefer

not (a and b)

not binds tighter than and, so without parentheses only a is negated.

Using or for defaults when 0 is valid

Avoid

quantity = given or 1 # 0 becomes 1

Prefer

quantity = given if given is not None else 1

or treats 0 and "" as missing because they are falsy.

Key takeaways

  • Evaluation order: parentheses, not, and, or.
  • and/or short-circuit and return an operand.
  • De Morgan: not (a and b) == not a or not b; not (a or b) == not a and not b.

Try it yourself

  1. 1
    Simplify: not (age < 18 or not has_id).
  2. 2
    Use a truth table loop to check whether a and (b or c) equals (a and b) or (a and c).

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic