Topic 37 of 64
and, or, not
Overview
Python uses the keywords 'and', 'or', 'not' instead of &&, ||, ! for logical operations. They short-circuit evaluate and return actual operand values (not just True/False) — enabling powerful idiomatic patterns.
Syntax
python
# and — returns first falsy or last value
True and True # True
True and False # False
"hello" and 42 # 42 (short-circuit: returns last)
# or — returns first truthy or last value
False or True # True
None or "default" # "default" (great for defaults!)
"value" or "default" # "value"
# not — inverts truthiness
not True # False
not [] # True (empty list is falsy)Common Pitfalls
- The 'or' default pattern fails if the value is legitimately 0, False, or '' — use the walrus operator or explicit None check instead: value if value is not None else default.
- Short-circuit means the right side may never execute: 'False and expensive_function()' never calls the function.
- Interview tip: Python's 'and'/'or' return operand values, not booleans — x = None or [] gives [] not False.
Real-World Example
Use 'or' for default values and 'and' for safe attribute access
example
python
def get_username(user: dict) -> str:
# 'or' for default value pattern
name = user.get("name") or "Anonymous"
# 'and' for safe chained access
email = user.get("profile") and user["profile"].get("email")
return f"{name} ({email or 'no email'})"
print(get_username({"name": "Alice", "profile": {"email": "a@x.com"}}))
# Alice (a@x.com)