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.
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.
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
“
andreturnsTrueonly if both operands are truthy;orreturnsTrueif at least one is;notinverts a boolean. Bothandandorshort-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, likex is not None and x.value, wherex.valueis only evaluated oncex is not Nonehas already confirmed it’s safe.”
Common Mistakes
- Assuming both operands of
and/orare always evaluated — short-circuiting means a function call used as the second operand may silently never run. - Writing
if x == True:orif x == False:instead ofif x:orif not x:— un-Pythonic and breaks for truthy/falsy values that aren’t literallyTrue/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