Guide Python Beginner

7.5 Logical Operators

Python's and, or, and not operators, their truth tables, and short-circuit evaluation — why the second operand is sometimes never executed at all.

2 min read
flowchart TD subgraph AND["and — True only if BOTH are truthy"] direction LR A1["True and True → True"] A2["True and False → False"] A3["False and True → False"] A4["False and False → False"] end subgraph OR["or — True if AT LEAST ONE is truthy"] direction LR O1["True or True → True"] O2["True or False → True"] O3["False or True → True"] O4["False or False → False"] end subgraph NOT["not — inverts"] direction LR N1["not True → False"] N2["not False → True"] end

Truth tables for and, or, and not.

and

Returns True only if both operands are truthy.

>>> True and False
False

or

Returns True if at least one operand is truthy.

>>> True or False
True

not

Inverts a boolean value.

>>> not True
False

Short-Circuit Evaluation

What Is It?

and/or stop evaluating as soon as the overall result is already determined by the first operand — the second operand is never even executed in that case.

Why Does It Matter?

Commonly exploited to avoid errors (checking x is not None and x.value safely) or to avoid unnecessary work.

flowchart LR subgraph AndCase["A and B — A = False"] A1["A = False"] -->|"short-circuits"| R1["Result: False\n(B never evaluated)"] end subgraph OrCase["A or B — A = True"] A2["A = True"] -->|"short-circuits"| R2["Result: True\n(B never evaluated)"] end

and stops at the first False; or stops at the first True.

def side_effect():
    print("called")
    return True

>>> False and side_effect()    # side_effect() is NEVER called
False
>>> True or side_effect()      # side_effect() is NEVER called
True

Quick Interview Answer

and returns True only if both operands are truthy; or returns True if at least one is; not inverts a boolean. Both and and or short-circuit — they stop evaluating as soon as the result is already determined, so the second operand may never actually execute. This is exploited deliberately to guard against errors, like x is not None and x.value, where x.value is only evaluated once x is not None has already confirmed it’s safe.”

Common Mistakes

  • Assuming both operands of and/or are always evaluated — short-circuiting means a function call used as the second operand may silently never run.
  • Writing if x == True: or if x == False: instead of if x: or if not x: — un-Pythonic and breaks for truthy/falsy values that aren’t literally True/False (see 7.10 Boolean Evaluation).

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form