How Python's "or" and "and" Operators Work

🔍 Python's Hidden Gem: Short-Circuit Evaluation with Operand Return Ever wondered why Python's "or" and "and" operators are more powerful than they seem? Unlike Java or C++, they don't just return True/False – they return the actual values! Short-circuit evaluation means that logical operators like and and or stop evaluating as soon as the result of the expression is known. In Python, these operators don’t just return True or False; they actually return the operand that determined the result — that’s what is meant by operand return. Python's logical operators ("or" and "and") return one of the actual operands, not necessarily True or False. The "or" Operator - - Returns the first truthy value it encounters - If all values are false, returns the last value The "and" Operator in Python - - Returns the first false value it encounters - If all values are truthy, returns the last value ``` # OR examples print(None or [1, 2, 3])   # [1, 2, 3] - returns first truthy print("hello" or "world")   # "hello" - returns first truthy print(False or 0 or [] or {}) # {} - all falsy, returns last print(42 or False)       # 42 - returns first truthy # AND examples   print([1, 2] and "text")    # "text" - all truthy, returns last print("text" and None)     # None - returns first falsy print(5 and 10 and 20)     # 20 - all truthy, returns last print(0 and [1, 2, 3])     # 0 - returns first falsy # Check if user exists AND has valid credentials OR is admin user = get_user(username) access_granted = (user and user.password == password) or is_admin # Returns: user object if password matches, False if not, or True if admin ``` False Values in Python (the complete list) : False None 0 (integer zero) 0.0 (float zero) 0j (complex zero) "" (empty string) [ ] (empty list) ( ) (empty tuple) { } (empty dict) set( ) (empty set) range(0) (empty range) Truth Values in Python (everything else!) : True Any non-zero number: 1, -1, 3.14, 2+3j Any non-empty string: "hello", "0", " " (even a space!) Any non-empty collection: [1, 2], (1,), {"a": 1} Any object or instance (by default) Functions, classes, modules ⚡ Why This Matters: - Reduces code complexity - Eliminates nested if-else pyramids - Makes default value handling elegant - Improves code readability dramatically #Python #CleanCode #CodingTips #SoftwareDevelopment

  • text

To view or add a comment, sign in

Explore content categories