Unlike some languages where and/or always produce a boolean, Python's `and` returns the first operand if it's falsy, otherwise the second operand, and `or` returns the first operand if it's truthy, otherwise the second — both short-circuit, meaning the second operand isn't even evaluated if the result is already determined by the first. This makes a pattern like falling back to a default value with `or` idiomatic in Python.
1Understanding Logical Operators
Unlike some languages where and/or always produce a boolean, Python's and returns the first operand if it's falsy, otherwise the second operand, and or returns the first operand if it's truthy, otherwise the second — both short-circuit, meaning the second operand isn't even evaluated if the result is already determined by the first. This makes a pattern like falling back to a default value with or idiomatic in Python.
Using `or` for a fallback value is a common idiom, but it treats any falsy value, like 0, an empty string, or an empty list, as 'missing', not just None — check explicitly for None instead when only that specific value should trigger the fallback.
print(True and False)
print(0 or "fallback")
print(not True)2Practical Example
Here is a real-world application of Logical Operators showing how it is used in production Python code.
user = None
name = user and user.get("name")
print(name)3Best Practices
Follow these guidelines when working with Logical Operators:
1. Use a or default for concise fallback values, but only when a falsy value like 0 or an empty string isn't itself meaningful for a
2. Rely on short-circuiting to avoid calling an expensive or error-prone function unnecessarily
3. Use not for boolean inversion instead of comparing explicitly to False
Tip: Using `or` for a fallback value is a common idiom, but it treats any falsy value, like 0, an empty string, or an empty list, as 'missing', not just None — check explicitly for None instead when only that specific value should trigger the fallback.
print(True and False)
print(0 or "fallback")
print(not True)