or — Intermediate Examples
Logical OR operator; returns True if at least one operand is true
Short-circuit and default values
Using 'or' to provide fallback values.
python
# or returns the first truthy value, or the last value print(0 or "default") print("" or "fallback") print(None or [] or "last resort") print("first" or "second") # Default value pattern name = "" display_name = name or "Anonymous" print(f"Hello, {display_name}") # Configuration defaults config = {} debug = config.get("debug") or False host = config.get("host") or "localhost" port = config.get("port") or 8080 print(f"{host}:{port} (debug={debug})")
Expected Output
default fallback last resort first Hello, Anonymous localhost:8080 (debug=False)
'or' short-circuits: it returns the first truthy value. This is a common pattern for default values, but beware: 0, False, and '' are all falsy.
or vs dict.get() vs ternary
Comparing different default value strategies.
python
# 'or' pitfall: 0 and False are falsy! count = 0 result = count or 10 # Bug: 0 is falsy, returns 10 print(f"or default: {result}") # Wrong! # Fix with ternary result = count if count is not None else 10 print(f"ternary: {result}") # Correct! # Fix with dict.get config = {"count": 0} result = config.get("count", 10) # Returns 0, not 10 print(f"dict.get: {result}") # Correct! # When 'or' is safe (None/empty string defaults) name = None print(name or "Unknown") # Safe: None is always falsy name = "" print(name or "Unknown") # Safe if empty string = no name
Expected Output
or default: 10 ternary: 0 dict.get: 0 Unknown Unknown
The 'or' default pattern fails when 0, False, or '' are valid values. Use ternary expressions or dict.get() when falsy values are legitimate.
Want to try these examples interactively?
Open Intermediate Playground