Python Logical Operators
In this page:
The and Operator
and evaluates to True only when both operands are true; if either side is false, the whole expression is false, making it the natural choice for combining two conditions that must *both* hold.
Example: The and Operator
print(True and False)
print(5 > 2 and 3 > 1)
The or Operator
or evaluates to True if at least one operand is true, and only fails when both sides are false — the right tool whenever any one of several conditions being met should trigger a result.
Example: The or Operator
print(True or False)
print(5 > 10 or 3 > 1)
The not Operator
not flips a boolean value: not True becomes False and vice versa, most often used to invert a condition cleanly rather than rewriting the comparison itself in its opposite form.
Example: The not Operator
print(not True)
Combining Logical Operators
Combining and, or, and not in one expression can get ambiguous quickly, so wrapping sub-conditions in parentheses — (a and b) or c — makes the intended evaluation order explicit to both Python and the next person reading the code.
Example: Combining Logical Operators
a, b, c = True, False, True
print((a and b) or c)
Short-circuit Evaluation
Python short-circuits logical evaluation: in a and b, if a is already false, b is never evaluated at all, and in a or b, if a is already true, b is skipped. This isn't just an optimization — code sometimes deliberately relies on it, like obj and obj.value to avoid an error on a None object.
Example: Short-circuit Evaluation
obj = None
print(obj and obj.upper())
Chapter Quiz — Complete all 16 topics to unlock
0/16 topics done
Complete these topics first:
- Python print()
- Python input()
- Python Format Strings
- Python f-strings
- Python String Formatting
- Python Arithmetic Operators
- Python Relational Operators
- Python Logical Operators
- Python Bitwise Operators
- Python Assignment Operators
- Python Increment & Decrement
- Python Ternary Operator
- Python Operator Precedence
- Python Identity Operators
- Python Membership Operators
- Python Operators