➕ Operators & Expressions
Module 3 · Topic 3
Logical Operators
Combine conditions with and, or, not — and understand short-circuit evaluation for writing efficient code.
Theory
Logical Operators:
| Operator | Description | Example |
|----------|-------------|--------|
| and | True if BOTH are True | True and False → False |
| or | True if EITHER is True | True or False → True |
| not | Inverts the boolean | not True → False |
Short-Circuit Evaluation:
Python stops evaluating as soon as the result is determined:
and: If first operand is False, second is NOT evaluatedor: If first operand is True, second is NOT evaluated
Return Values (NOT just True/False!):
andreturns the first falsy value, or the last value if all truthyorreturns the first truthy value, or the last value if all falsy
Examples:
"hello" and "world"→"world"(both truthy, returns last)"" and "world"→""(first is falsy, returns it)"" or "default"→"default"(first falsy, returns second)"hello" or "default"→"hello"(first truthy, returns it)
This is commonly used for default values: name = user_input or "Anonymous"
Syntax
x and y # True if both True
x or y # True if either True
not x # Inverts boolean
# Short-circuit for defaults
value = user_input or "default"
# Short-circuit for safe access
result = obj and obj.method()