Practical Applications
def validate_user_registration(username, email, age):
"""Comprehensive user registration validation"""
is_valid_username = len(username) >= 3 and len(username) <= 20
is_valid_email = '@' in email and '.' in email
is_valid_age = age >= 18 and age <= 100
return is_valid_username and is_valid_email and is_valid_age
## LabEx Example
print(validate_user_registration("john_doe", "[email protected]", 25)) ## True
print(validate_user_registration("ab", "invalid", 15)) ## False
Access Control System
def check_system_access(user_role, is_authenticated, has_permission):
"""Implement multi-level access control"""
admin_access = user_role == "admin"
standard_access = is_authenticated and has_permission
return admin_access or standard_access
## Access scenarios
print(check_system_access("admin", False, False)) ## True
print(check_system_access("user", True, True)) ## True
print(check_system_access("user", False, True)) ## False
Conditional Data Processing
def process_transaction(amount, is_verified, balance):
"""Implement transaction processing logic"""
can_process = (is_verified and amount > 0) and (balance >= amount)
return "Transaction Approved" if can_process else "Transaction Denied"
## Transaction scenarios
print(process_transaction(100, True, 500)) ## Transaction Approved
print(process_transaction(600, True, 500)) ## Transaction Denied
Boolean Logic Workflow
graph TD
A[Input Data] --> B{Validation Checks}
B --> |Pass| C[Process Data]
B --> |Fail| D[Reject/Error Handling]
Advanced Filtering Technique
def filter_advanced_users(users):
"""Filter users based on multiple criteria"""
advanced_users = [
user for user in users
if user['age'] >= 25 and
user['experience'] > 3 and
user['certification'] is True
]
return advanced_users
## Sample user data
users = [
{'name': 'Alice', 'age': 30, 'experience': 5, 'certification': True},
{'name': 'Bob', 'age': 22, 'experience': 2, 'certification': False}
]
print(filter_advanced_users(users))
Error Handling with Boolean Logic
def safe_division(a, b):
"""Implement safe division with error handling"""
return a / b if b != 0 else None
def complex_calculation(x, y):
"""Demonstrate complex boolean error handling"""
division_result = safe_division(x, y)
return division_result * 2 if division_result is not None else "Invalid Operation"
## LabEx Error Handling Example
print(complex_calculation(10, 2)) ## 10.0
print(complex_calculation(10, 0)) ## Invalid Operation
Technique |
Description |
Example |
Short-Circuit |
Stops evaluation when result is determined |
x and y() |
Lazy Evaluation |
Computes only when necessary |
any() , all() |
Minimal Checks |
Reduce unnecessary computations |
Ordered boolean conditions |
Key Takeaways
- Boolean logic is crucial for robust software design
- Implement comprehensive validation strategies
- Use short-circuit evaluation for efficiency
- Create flexible, maintainable conditional logic