
Python
Master boolean algebra, operator precedence, truthiness, and advanced logical patterns.
Boolean algebra is the foundation of logical reasoning in programming.
# De Morgan's Laws: Equivalences for simplifying boolean expressions
# NOT (A AND B) == (NOT A) OR (NOT B)
# NOT (A OR B) == (NOT A) AND (NOT B)
A, B = True, False
# Example 1: De Morgan's First Law
print(not (A and B)) # True
print((not A) or (not B)) # True (equivalent)
# Example 2: De Morgan's Second Law
print(not (A or B)) # False
print((not A) and (not B)) # False (equivalent)
# Practical use: Simplifying complex conditions
# Instead of: if not (user_logged_in and has_permission):
# Write: if not user_logged_in or not has_permission:# Operator precedence (highest to lowest)
# 1. not
# 2. and
# 3. or
# Without parentheses
print(True or False and False) # True (and evaluated first)
print((True or False) and False) # False (or evaluated first)
# Short-circuit evaluation: Stop evaluating when result is determined
def side_effect():
print("This is evaluated")
return True
# AND short-circuit: stops if first operand is False
print(False and side_effect()) # "This is evaluated" not printed
# OR short-circuit: stops if first operand is True
print(True or side_effect()) # "This is evaluated" not printed
# Always evaluated
print(True and side_effect()) # "This is evaluated" printed
print(False or side_effect()) # "This is evaluated" printed
# Performance optimization using short-circuit
def expensive_check():
# Simulate expensive operation
return some_condition()
if quick_check() and expensive_check(): # expensive_check only if quick_check is True
pass# Falsy values in Python
falsy_values = [
False, # Boolean False
None, # None object
0, 0.0, 0j, # Zero (int, float, complex)
"", b"", [], # Empty sequences and collections
{}, set(), # Empty dict and set
]
for value in falsy_values:
print(f"{value!r:20} → bool: {bool(value)}")
# Truthy values: Everything else
truthy_values = [
True,
1, -1, 0.1, # Non-zero numbers
"0", "False", # Non-empty strings (even if content is falsy)
[0], {"": None}, # Non-empty collections (even with falsy contents)
]
# Key insight: "0" is truthy because it's a non-empty string
print(bool("0")) # True
print(bool("False")) # TrueCommon mistake:
# Wrong: Testing integer with truthiness
if user_id: # Works if user_id > 0, fails if user_id == 0
print("Valid user")
# Right: Explicit comparison
if user_id is not None: # Correct for checking existence
print("Valid user")
if user_id > 0: # Explicit for numeric comparison
print("Valid positive user")# None is a singleton: only one None object exists
x = None
y = None
print(x is y) # True (same object)
# Correct None checking
value = 0
# ✗ Wrong
if not value: # False for 0, empty string, etc.
print("Checking for 0, empty string, etc.")
# ✓ Right
if value is None: # Only True if value is None
print("Value is None")
# Type checking for None
print(type(None)) # <class 'NoneType'>
print(isinstance(None, type(None))) # True
# Default parameter handling
def function(param=None):
if param is None:
param = [] # Initialize mutable default safely
return param
# ✗ Wrong (mutable default argument)
def bad_function(param=[]): # Shared across calls!
param.append(1)
return param
print(bad_function()) # [1]
print(bad_function()) # [1, 1] ← Unexpected!
# ✓ Right
def good_function(param=None):
if param is None:
param = []
param.append(1)
return param
print(good_function()) # [1]
print(good_function()) # [1] ← CorrectConditional expressions (ternary operator):
# Basic ternary
age = 25
status = "adult" if age >= 18 else "minor"
# Chained ternary (use with caution)
score = 85
grade = "A" if score >= 90 else "B" if score >= 80 else "C"
# Using and/or for defaults (pre-ternary pattern)
name = user_input or "Guest" # "Guest" if user_input is falsy
# Better: Use ternary for clarity
name = user_input if user_input else "Guest"Boolean return optimization:
# ✓ Pythonic: return comparison result directly
def is_positive(num):
return num > 0 # Returns boolean
# ✗ Verbose: unnecessary if/else
def is_positive_verbose(num):
if num > 0:
return True
else:
return FalseUsing all() and any():
# all(): True if all elements are truthy
print(all([True, True, True])) # True
print(all([True, False, True])) # False
print(all([])) # True (empty is all)
# any(): True if any element is truthy
print(any([False, False, False])) # False
print(any([False, True, False])) # True
print(any([])) # False (empty has none)
# Practical use
numbers = [2, 4, 6, 8]
if all(x % 2 == 0 for x in numbers): # All even?
print("All numbers are even")
if any(x < 0 for x in numbers): # Any negative?
print("At least one negative")| Concept | Remember |
|---|---|
| Truthy/Falsy | Empty containers, 0, None, False are falsy |
| is vs == | Use `is None`, `is True/False` for identity; `==` for value |
| Short-circuit | Exploit to avoid expensive operations |
| De Morgan's Laws | Simplify complex boolean expressions |
| all()/any() | Efficient bulk boolean checks |
Explore Type Conversion for advanced type system patterns.
Ready to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward