andAdvanced Examples

Logical AND operator; returns True if both operands are true

and in functional patterns

Using and for conditional execution.

python
# and as a functional guard
def safe_head(lst):
    return lst and lst[0]

print(safe_head([1, 2, 3]))
print(safe_head([]))

# Conditional method call
class Logger:
    def __init__(self, enabled):
        self.enabled = enabled
    def log(self, msg):
        self.enabled and print(f"LOG: {msg}")

logger = Logger(True)
logger.log("active")

logger = Logger(False)
logger.log("suppressed")  # prints nothing

# De Morgan's laws
a, b = True, False
print(f"not (a and b) = {not (a and b)}")
print(f"(not a) or (not b) = {(not a) or (not b)}")
Expected Output
1
[]
LOG: active
not (a and b) = True
(not a) or (not b) = True

Using 'and' for side effects (like method calls) is a pattern from JavaScript. In Python, explicit if statements are usually preferred for clarity.

Want to try these examples interactively?

Open Advanced Playground