How to writing multiple conditions in python
How to Write Multiple Conditions in Python
Writing multiple conditions is a fundamental skill in Python programming that allows you to create sophisticated decision-making logic in your applications. Whether you're building simple scripts or complex software systems, understanding how to properly combine and evaluate multiple conditions is essential for creating robust, maintainable code.
This comprehensive guide will walk you through everything you need to know about writing multiple conditions in Python, from basic logical operators to advanced techniques used by professional developers.
Table of Contents
1. [Prerequisites](#prerequisites)
2. [Understanding Logical Operators](#understanding-logical-operators)
3. [Basic Multiple Conditions with if Statements](#basic-multiple-conditions-with-if-statements)
4. [Using elif for Multiple Exclusive Conditions](#using-elif-for-multiple-exclusive-conditions)
5. [Combining Conditions with Logical Operators](#combining-conditions-with-logical-operators)
6. [Advanced Conditional Techniques](#advanced-conditional-techniques)
7. [Real-World Examples and Use Cases](#real-world-examples-and-use-cases)
8. [Common Pitfalls and Troubleshooting](#common-pitfalls-and-troubleshooting)
9. [Best Practices and Professional Tips](#best-practices-and-professional-tips)
10. [Conclusion](#conclusion)
Prerequisites
Before diving into multiple conditions, you should have:
- Basic understanding of Python syntax
- Knowledge of variables and data types
- Familiarity with comparison operators (`==`, `!=`, `<`, `>`, `<=`, `>=`)
- Understanding of boolean values (`True` and `False`)
- Basic knowledge of if statements
Understanding Logical Operators
Python provides three primary logical operators for combining multiple conditions:
The `and` Operator
The `and` operator returns `True` only when both conditions are true:
```python
Basic and operator usage
age = 25
has_license = True
if age >= 18 and has_license:
print("You can drive!")
else:
print("You cannot drive.")
```
Truth Table for `and`:
- `True and True` = `True`
- `True and False` = `False`
- `False and True` = `False`
- `False and False` = `False`
The `or` Operator
The `or` operator returns `True` when at least one condition is true:
```python
Basic or operator usage
is_weekend = True
is_holiday = False
if is_weekend or is_holiday:
print("No work today!")
else:
print("Time to work.")
```
Truth Table for `or`:
- `True or True` = `True`
- `True or False` = `True`
- `False or True` = `True`
- `False or False` = `False`
The `not` Operator
The `not` operator reverses the boolean value:
```python
Basic not operator usage
is_raining = False
if not is_raining:
print("Perfect day for a picnic!")
else:
print("Better stay inside.")
```
Truth Table for `not`:
- `not True` = `False`
- `not False` = `True`
Basic Multiple Conditions with if Statements
Simple Multiple if Statements
You can use multiple separate if statements when you need to check independent conditions:
```python
score = 85
attendance = 90
participation = 75
Multiple independent conditions
if score >= 80:
print("Excellent test performance!")
if attendance >= 85:
print("Great attendance!")
if participation >= 70:
print("Good participation!")
```
Nested if Statements
Nested if statements allow you to create hierarchical decision structures:
```python
weather = "sunny"
temperature = 75
has_umbrella = True
if weather == "sunny":
if temperature > 70:
print("Perfect day for outdoor activities!")
else:
print("Sunny but a bit chilly.")
elif weather == "rainy":
if has_umbrella:
print("You're prepared for the rain!")
else:
print("You might get wet!")
```
Using elif for Multiple Exclusive Conditions
The `elif` (else if) statement is perfect when you have multiple mutually exclusive conditions:
Basic elif Structure
```python
grade = 87
if grade >= 90:
letter_grade = "A"
elif grade >= 80:
letter_grade = "B"
elif grade >= 70:
letter_grade = "C"
elif grade >= 60:
letter_grade = "D"
else:
letter_grade = "F"
print(f"Your grade is: {letter_grade}")
```
Multiple elif Statements with Complex Conditions
```python
user_role = "admin"
user_department = "IT"
years_experience = 5
if user_role == "admin" and user_department == "IT":
access_level = "full_system"
elif user_role == "manager" and years_experience >= 3:
access_level = "departmental"
elif user_role == "employee" and user_department in ["HR", "Finance"]:
access_level = "restricted_sensitive"
elif user_role == "employee":
access_level = "basic"
else:
access_level = "no_access"
print(f"Access level: {access_level}")
```
Combining Conditions with Logical Operators
Using `and` for Multiple Requirements
When all conditions must be true:
```python
def can_apply_for_loan(age, income, credit_score, employment_years):
"""Check if someone qualifies for a loan"""
if (age >= 21 and
income >= 30000 and
credit_score >= 650 and
employment_years >= 2):
return True
else:
return False
Test the function
applicant_qualified = can_apply_for_loan(28, 45000, 720, 3)
print(f"Loan qualification: {applicant_qualified}") # True
```
Using `or` for Alternative Conditions
When any condition can satisfy the requirement:
```python
def is_eligible_for_discount(is_student, is_senior, is_military, is_member):
"""Check if someone qualifies for a discount"""
if is_student or is_senior or is_military or is_member:
return True
else:
return False
Test the function
gets_discount = is_eligible_for_discount(True, False, False, False)
print(f"Eligible for discount: {gets_discount}") # True
```
Combining `and` and `or` Operators
Use parentheses to group conditions and control evaluation order:
```python
def can_access_system(user_type, department, clearance_level, is_weekend):
"""Complex access control logic"""
if ((user_type == "employee" and department == "Security") or
(user_type == "contractor" and clearance_level >= 3) or
(user_type == "admin")) and not is_weekend:
return True
else:
return False
Test various scenarios
print(can_access_system("employee", "Security", 1, False)) # True
print(can_access_system("contractor", "IT", 4, False)) # True
print(can_access_system("admin", "Any", 1, False)) # True
print(can_access_system("employee", "Security", 1, True)) # False (weekend)
```
Advanced Conditional Techniques
Using `in` and `not in` Operators
Check membership in collections:
```python
def categorize_day(day):
"""Categorize days of the week"""
weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
weekends = ["Saturday", "Sunday"]
if day in weekdays:
return "Workday"
elif day in weekends:
return "Weekend"
else:
return "Invalid day"
print(categorize_day("Friday")) # Workday
print(categorize_day("Sunday")) # Weekend
```
Conditional Expressions (Ternary Operator)
For simple conditions, use the ternary operator:
```python
Traditional if-else
age = 20
if age >= 18:
status = "adult"
else:
status = "minor"
Ternary operator (more concise)
status = "adult" if age >= 18 else "minor"
Multiple ternary conditions
temperature = 75
weather_description = (
"Hot" if temperature > 80 else
"Warm" if temperature > 65 else
"Cool" if temperature > 45 else
"Cold"
)
```
Using `all()` and `any()` Functions
For checking multiple conditions in sequences:
```python
def validate_password(password):
"""Validate password with multiple criteria"""
checks = [
len(password) >= 8,
any(c.isupper() for c in password),
any(c.islower() for c in password),
any(c.isdigit() for c in password),
any(c in "!@#$%^&*" for c in password)
]
if all(checks):
return "Strong password"
elif sum(checks) >= 3:
return "Moderate password"
else:
return "Weak password"
print(validate_password("MyPass123!")) # Strong password
print(validate_password("password")) # Weak password
```
Match-Case Statements (Python 3.10+)
For multiple discrete conditions, consider using match-case:
```python
def process_http_status(status_code):
"""Process HTTP status codes using match-case"""
match status_code:
case 200:
return "Success"
case 201:
return "Created"
case 400 | 401 | 403: # Multiple values
return "Client Error"
case 404:
return "Not Found"
case 500 | 502 | 503:
return "Server Error"
case code if 200 <= code < 300: # Range condition
return "Success Range"
case _: # Default case
return "Unknown Status"
print(process_http_status(200)) # Success
print(process_http_status(401)) # Client Error
```
Real-World Examples and Use Cases
Example 1: E-commerce Shipping Calculator
```python
def calculate_shipping(weight, distance, is_express, is_member, order_total):
"""Calculate shipping cost based on multiple conditions"""
base_rate = 5.00
# Weight-based pricing
if weight <= 1:
weight_cost = 2.00
elif weight <= 5:
weight_cost = 5.00
elif weight <= 10:
weight_cost = 8.00
else:
weight_cost = 12.00
# Distance-based pricing
if distance <= 100:
distance_cost = 3.00
elif distance <= 500:
distance_cost = 7.00
else:
distance_cost = 12.00
total_cost = base_rate + weight_cost + distance_cost
# Apply modifiers
if is_express:
total_cost *= 1.5
if is_member and order_total >= 50:
total_cost *= 0.8 # 20% discount
elif order_total >= 100:
total_cost = 0 # Free shipping
return round(total_cost, 2)
Test the function
shipping_cost = calculate_shipping(
weight=3,
distance=150,
is_express=True,
is_member=True,
order_total=75
)
print(f"Shipping cost: ${shipping_cost}")
```
Example 2: User Authentication System
```python
class UserAuthenticator:
def __init__(self):
self.max_attempts = 3
self.lockout_duration = 300 # 5 minutes in seconds
def authenticate_user(self, username, password, failed_attempts,
last_attempt_time, current_time, is_admin=False):
"""Comprehensive user authentication with multiple conditions"""
# Check if account is locked
time_since_last_attempt = current_time - last_attempt_time
if (failed_attempts >= self.max_attempts and
time_since_last_attempt < self.lockout_duration):
return {
"success": False,
"message": "Account temporarily locked due to multiple failed attempts"
}
# Validate credentials (simplified)
if not self._validate_credentials(username, password):
return {
"success": False,
"message": "Invalid username or password"
}
# Additional checks for admin users
if is_admin and not self._validate_admin_requirements(username):
return {
"success": False,
"message": "Admin authentication requires additional verification"
}
# Success
return {
"success": True,
"message": "Authentication successful"
}
def _validate_credentials(self, username, password):
# Simplified credential validation
return len(username) > 0 and len(password) >= 8
def _validate_admin_requirements(self, username):
# Additional admin validation logic
return username.endswith("_admin")
```
Example 3: Data Processing Pipeline
```python
def process_data_record(record):
"""Process a data record with multiple validation conditions"""
errors = []
warnings = []
# Required field validation
required_fields = ["id", "name", "email", "age"]
for field in required_fields:
if field not in record or record[field] is None:
errors.append(f"Missing required field: {field}")
# If we have errors, return early
if errors:
return {"status": "error", "errors": errors, "warnings": warnings}
# Data type and format validation
if not isinstance(record["age"], int) or record["age"] < 0:
errors.append("Age must be a positive integer")
if "@" not in record["email"] or "." not in record["email"]:
errors.append("Invalid email format")
# Business logic validation
if record["age"] < 13 and "parent_consent" not in record:
errors.append("Users under 13 require parent consent")
elif record["age"] < 18:
warnings.append("User is a minor")
# Determine final status
if errors:
status = "error"
elif warnings:
status = "warning"
else:
status = "success"
return {
"status": status,
"errors": errors,
"warnings": warnings,
"processed_record": record if status != "error" else None
}
Test the function
test_record = {
"id": 123,
"name": "John Doe",
"email": "john@example.com",
"age": 16
}
result = process_data_record(test_record)
print(f"Processing result: {result}")
```
Common Pitfalls and Troubleshooting
Pitfall 1: Operator Precedence Issues
Problem:
```python
Incorrect - may not behave as expected
if age > 18 and income > 30000 or credit_score > 700:
approve_loan()
```
Solution:
```python
Correct - use parentheses for clarity
if (age > 18 and income > 30000) or credit_score > 700:
approve_loan()
```
Pitfall 2: Comparing Different Data Types
Problem:
```python
user_input = input("Enter your age: ") # Returns string
if user_input > 18: # Comparing string to integer
print("You're an adult")
```
Solution:
```python
try:
age = int(input("Enter your age: "))
if age > 18:
print("You're an adult")
except ValueError:
print("Please enter a valid number")
```
Pitfall 3: Using Assignment Instead of Comparison
Problem:
```python
if status = "active": # Assignment, not comparison
process_user()
```
Solution:
```python
if status == "active": # Comparison
process_user()
```
Pitfall 4: Short-Circuit Evaluation Misunderstanding
Problem:
```python
This might cause an error if items is empty
if len(items) > 0 and items[0] == "start":
process_items()
```
Solution:
```python
Better approach
if items and items[0] == "start":
process_items()
```
Pitfall 5: Complex Nested Conditions
Problem:
```python
Hard to read and maintain
if user_type == "admin":
if department == "IT":
if experience > 5:
if has_certification:
grant_access()
```
Solution:
```python
More readable
def can_grant_access(user_type, department, experience, has_certification):
return (user_type == "admin" and
department == "IT" and
experience > 5 and
has_certification)
if can_grant_access(user_type, department, experience, has_certification):
grant_access()
```
Best Practices and Professional Tips
1. Use Descriptive Variable Names
```python
Poor
if a > 18 and b and c > 600:
return True
Better
if age > 18 and has_income and credit_score > 600:
return True
```
2. Extract Complex Conditions into Functions
```python
def is_eligible_for_premium(user):
"""Check if user is eligible for premium features"""
return (user.age >= 18 and
user.subscription_type in ["gold", "platinum"] and
user.account_status == "active" and
user.payment_method is not None)
Usage
if is_eligible_for_premium(current_user):
enable_premium_features()
```
3. Use Early Returns to Reduce Nesting
```python
def process_order(order):
"""Process an order with multiple validation steps"""
# Early returns for error conditions
if not order:
return {"error": "Order is required"}
if order.total <= 0:
return {"error": "Order total must be positive"}
if not order.customer:
return {"error": "Customer information is required"}
# Main processing logic here
return {"success": True, "order_id": order.id}
```
4. Use Configuration for Complex Business Rules
```python
class LoanApprovalConfig:
MIN_AGE = 21
MAX_AGE = 65
MIN_INCOME = 30000
MIN_CREDIT_SCORE = 650
MIN_EMPLOYMENT_YEARS = 2
def can_approve_loan(applicant, config=LoanApprovalConfig):
"""Check loan approval with configurable rules"""
return (config.MIN_AGE <= applicant.age <= config.MAX_AGE and
applicant.income >= config.MIN_INCOME and
applicant.credit_score >= config.MIN_CREDIT_SCORE and
applicant.employment_years >= config.MIN_EMPLOYMENT_YEARS)
```
5. Document Complex Conditional Logic
```python
def calculate_insurance_premium(age, driving_record, vehicle_type, coverage_level):
"""
Calculate insurance premium based on multiple factors
Premium calculation rules:
- Base rate varies by age group (under 25, 25-65, over 65)
- Driving record multiplier: clean (1.0), minor violations (1.2), major violations (1.8)
- Vehicle type multiplier: economy (0.9), standard (1.0), luxury (1.3), sports (1.6)
- Coverage level multiplier: basic (0.8), standard (1.0), comprehensive (1.4)
"""
# Age-based base rate
if age < 25:
base_rate = 1200
elif age <= 65:
base_rate = 800
else:
base_rate = 1000
# Apply multipliers based on other factors
# ... implementation details
return calculated_premium
```
6. Use Type Hints for Better Code Documentation
```python
from typing import Optional
def validate_user_permissions(
user_role: str,
department: str,
clearance_level: int,
is_temporary: bool = False
) -> Optional[str]:
"""
Validate user permissions and return access level
Returns:
Optional[str]: Access level or None if no access
"""
if user_role == "admin" and clearance_level >= 5:
return "full_access"
elif user_role == "manager" and department in ["HR", "Finance"]:
return "departmental_access"
elif not is_temporary and clearance_level >= 3:
return "standard_access"
else:
return None
```
Performance Considerations
Short-Circuit Evaluation
Python uses short-circuit evaluation, which can improve performance:
```python
Expensive operation only runs if cheap_condition is True
if cheap_condition() and expensive_operation():
do_something()
Check most likely conditions first
if common_case or rare_case_1 or rare_case_2:
handle_case()
```
Avoid Repeated Calculations
```python
Inefficient - calculates multiple times
if calculate_score(data) > 80 and calculate_score(data) < 95:
process_data()
Efficient - calculate once
score = calculate_score(data)
if 80 < score < 95:
process_data()
```
Testing Multiple Conditions
Unit Testing Example
```python
import unittest
class TestUserPermissions(unittest.TestCase):
def test_admin_access(self):
"""Test admin users get full access"""
result = check_access("admin", "IT", 5, False)
self.assertEqual(result, "full_access")
def test_temporary_user_restrictions(self):
"""Test temporary users have limited access"""
result = check_access("employee", "Engineering", 4, True)
self.assertNotEqual(result, "full_access")
def test_invalid_combinations(self):
"""Test invalid parameter combinations"""
result = check_access("unknown_role", "IT", 1, False)
self.assertIsNone(result)
if __name__ == "__main__":
unittest.main()
```
Conclusion
Writing multiple conditions in Python is a crucial skill that enables you to create sophisticated, decision-making logic in your applications. Throughout this guide, we've covered:
- Fundamental logical operators (`and`, `or`, `not`) and their proper usage
- Control flow structures including if-elif-else chains and nested conditions
- Advanced techniques such as ternary operators, `all()`/`any()` functions, and match-case statements
- Real-world applications demonstrating practical implementation patterns
- Common pitfalls and how to avoid them
- Best practices for writing maintainable, readable conditional code
Key Takeaways
1. Clarity over cleverness: Write conditions that are easy to read and understand
2. Use parentheses to make operator precedence explicit
3. Extract complex logic into well-named functions
4. Consider performance by ordering conditions strategically
5. Test thoroughly to ensure all condition combinations work correctly
6. Document complex business rules to help future maintainers
Next Steps
To further improve your conditional logic skills:
- Practice with more complex real-world scenarios
- Learn about design patterns like Strategy and State patterns
- Explore functional programming concepts like guard clauses
- Study existing codebases to see how experienced developers structure conditions
- Consider using static analysis tools to catch potential issues in conditional logic
Remember that well-written conditional logic is not just about making your code workâit's about making it maintainable, testable, and understandable for both current and future developers. As you continue to develop your Python skills, these principles will serve as a foundation for writing professional-quality code.