Practical Techniques
Conditional Logic in Real-World Scenarios
Data Validation
def validate_user_input(username, password):
if not username or len(username) < 3:
return False, "Username too short"
if not password or len(password) < 8:
return False, "Password too weak"
return True, "Valid credentials"
## Usage
status, message = validate_user_input("john", "short")
print(message) ## Outputs: Password too weak
Efficient Condition Handling
Using Dictionary Mapping
def get_day_type(day):
day_types = {
'Monday': 'Workday',
'Tuesday': 'Workday',
'Wednesday': 'Workday',
'Thursday': 'Workday',
'Friday': 'Workday',
'Saturday': 'Weekend',
'Sunday': 'Weekend'
}
return day_types.get(day, 'Invalid day')
print(get_day_type('Monday')) ## Outputs: Workday
Conditional Workflow Management
graph TD
A[Start] --> B{Input Validation}
B -->|Valid| C[Process Data]
B -->|Invalid| D[Show Error]
C --> E[Generate Result]
D --> F[Request Retry]
E --> G[End]
Advanced Condition Strategies
Strategy |
Description |
Use Case |
Early Return |
Exit function early |
Reducing nested conditions |
Guard Clauses |
Handle edge cases first |
Improving code readability |
Default Arguments |
Provide fallback values |
Simplifying function logic |
Guard Clause Example
def process_user_data(user):
if not user:
return None
if not user.get('name'):
return None
## Process valid user data
return user['name'].upper()
Context-Based Conditional Logic
class PaymentProcessor:
def process_payment(self, amount, payment_method):
methods = {
'credit': self._process_credit,
'debit': self._process_debit,
'paypal': self._process_paypal
}
handler = methods.get(payment_method)
return handler(amount) if handler else None
Avoiding Repeated Conditions
## Less Efficient
def check_range(x):
if x > 0 and x < 100:
return True
return False
## More Efficient
def check_range(x):
return 0 < x < 100
Error Handling Patterns
def safe_division(a, b):
try:
return a / b
except ZeroDivisionError:
return None
except TypeError:
return 0
Best Practices
- Keep conditions simple and readable
- Use meaningful variable names
- Prefer built-in Python constructs
- Test edge cases thoroughly
LabEx recommends practicing these techniques to write more robust and maintainable Python code.