Writing Multiple Conditions in Python
Table of Contents
1. [Introduction](#introduction) 2. [Basic Logical Operators](#basic-logical-operators) 3. [Comparison Operators](#comparison-operators) 4. [Combining Multiple Conditions](#combining-multiple-conditions) 5. [Complex Conditional Structures](#complex-conditional-structures) 6. [Advanced Techniques](#advanced-techniques) 7. [Best Practices](#best-practices) 8. [Common Pitfalls](#common-pitfalls) 9. [Performance Considerations](#performance-considerations) 10. [Practical Examples](#practical-examples)Introduction
Writing multiple conditions in Python is a fundamental skill that allows developers to create sophisticated decision-making logic in their programs. Python provides various operators and structures to combine and evaluate multiple conditions efficiently. Understanding how to properly construct and evaluate multiple conditions is crucial for writing robust, readable, and maintainable code.
Multiple conditions enable programs to make complex decisions based on various factors, validate input data comprehensively, control program flow precisely, and implement business logic accurately. This comprehensive guide covers all aspects of working with multiple conditions in Python, from basic concepts to advanced techniques.
Basic Logical Operators
Python provides three primary logical operators for combining conditions: and, or, and not. These operators follow Boolean logic principles and are essential for constructing multiple condition statements.
The and Operator
The and operator returns True only when both conditions are true. It implements short-circuit evaluation, meaning if the first condition is false, the second condition is not evaluated.
`python
Basic and operator usage
age = 25 income = 50000Both conditions must be true
if age >= 18 and income >= 30000: print("Eligible for loan") else: print("Not eligible for loan")Multiple and conditions
score = 85 attendance = 90 behavior = "good"if score >= 80 and attendance >= 85 and behavior == "good":
print("Student receives honors")
`
The or Operator
The or operator returns True when at least one condition is true. It also uses short-circuit evaluation, stopping evaluation once a true condition is found.
`python
Basic or operator usage
day = "Saturday" holiday = TrueEither condition can be true
if day in ["Saturday", "Sunday"] or holiday: print("No work today")Multiple or conditions
weather = "sunny" temperature = 75 mood = "happy"if weather == "sunny" or temperature > 70 or mood == "happy":
print("Good day for outdoor activities")
`
The not Operator
The not operator negates a condition, returning the opposite boolean value.
`python
Basic not operator usage
logged_in = False premium_user = TrueNegating conditions
if not logged_in: print("Please log in to continue")if not premium_user: print("Upgrade to premium for additional features")
Combining not with other operators
if not (age < 18 or income < 20000): print("Meets minimum requirements")`Comparison Operators
Comparison operators are used to compare values and form the building blocks of conditions. Understanding these operators is essential for creating meaningful multiple condition statements.
| Operator | Description | Example | Result |
|----------|-------------|---------|---------|
| == | Equal to | 5 == 5 | True |
| != | Not equal to | 5 != 3 | True |
| < | Less than | 3 < 5 | True |
| <= | Less than or equal to | 5 <= 5 | True |
| > | Greater than | 7 > 3 | True |
| >= | Greater than or equal to | 5 >= 5 | True |
| in | Membership test | 'a' in 'apple' | True |
| not in | Negative membership | 'z' not in 'apple' | True |
| is | Identity comparison | x is None | Varies |
| is not | Negative identity | x is not None | Varies |
Practical Examples of Comparison Operators
`python
Numeric comparisons
price = 29.99 budget = 50.00 discount = 0.1if price <= budget and discount > 0: final_price = price * (1 - discount) print(f"Discounted price: ${final_price:.2f}")
String comparisons
username = "john_doe" password = "secure123" min_password_length = 8if len(username) >= 3 and len(password) >= min_password_length: print("Valid credentials format")
Membership testing
allowed_extensions = ['.jpg', '.png', '.gif', '.pdf'] filename = "document.pdf" file_extension = filename[filename.rfind('.'):]if file_extension.lower() in allowed_extensions and len(filename) > 0:
print("File type accepted")
`
Combining Multiple Conditions
When working with multiple conditions, proper grouping and operator precedence become crucial. Python evaluates expressions according to specific precedence rules, but explicit parentheses improve readability and ensure correct evaluation order.
Operator Precedence Table
| Priority | Operator | Description |
|----------|----------|-------------|
| 1 | () | Parentheses (highest) |
| 2 | not | Logical NOT |
| 3 | and | Logical AND |
| 4 | or | Logical OR (lowest) |
Complex Condition Examples
`python
Example 1: User authentication system
username = "admin" password = "password123" is_active = True login_attempts = 2 max_attempts = 3 account_locked = FalseComplex authentication logic
if (username == "admin" and password == "password123" and is_active and login_attempts < max_attempts and not account_locked): print("Login successful") login_attempts = 0 elif login_attempts >= max_attempts or account_locked: print("Account locked due to too many failed attempts") else: print("Invalid credentials") login_attempts += 1Example 2: Grade calculation system
midterm_score = 85 final_score = 92 attendance_rate = 0.95 assignment_average = 88 extra_credit = 5Multiple conditions for grade determination
if (midterm_score >= 90 and final_score >= 90 and attendance_rate >= 0.9 and assignment_average >= 85): grade = "A" elif (midterm_score >= 80 and final_score >= 80 and attendance_rate >= 0.8 and assignment_average >= 75) or extra_credit >= 10: grade = "B" elif (midterm_score >= 70 and final_score >= 70 and attendance_rate >= 0.7): grade = "C" else: grade = "F"print(f"Final grade: {grade}")
`
Using Parentheses for Clarity
`python
Without parentheses - potentially confusing
age = 25 income = 45000 credit_score = 720 employment_years = 3Ambiguous precedence
if age >= 21 and income >= 40000 or credit_score >= 700 and employment_years >= 2: print("Loan approved")With parentheses - clear intention
if (age >= 21 and income >= 40000) or (credit_score >= 700 and employment_years >= 2): print("Loan approved")More complex grouping
student = True senior = False military = False income_low = TrueClear grouping for discount eligibility
if ((student or senior or military) and income_low) or (senior and military): discount_rate = 0.2 print(f"Discount applied: {discount_rate * 100}%")`Complex Conditional Structures
Beyond simple if-elif-else statements, Python offers several ways to handle complex conditional logic efficiently and readably.
Nested Conditions
`python
Example: Online shopping cart validation
cart_total = 150.00 shipping_country = "USA" payment_method = "credit_card" user_type = "premium" coupon_code = "SAVE20"if cart_total > 0:
if shipping_country in ["USA", "Canada", "UK"]:
if payment_method in ["credit_card", "paypal", "apple_pay"]:
base_shipping = 10.00
if user_type == "premium":
shipping_cost = 0 # Free shipping for premium users
elif cart_total >= 100:
shipping_cost = 0 # Free shipping over $100
else:
shipping_cost = base_shipping
# Apply coupon if valid
if coupon_code == "SAVE20" and cart_total >= 50:
discount = cart_total * 0.20
final_total = cart_total - discount + shipping_cost
else:
final_total = cart_total + shipping_cost
print(f"Order total: ${final_total:.2f}")
else:
print("Payment method not accepted")
else:
print("Shipping not available to this country")
else:
print("Cart is empty")
`
Multiple Condition Patterns
`python
Pattern 1: Range checking
def categorize_temperature(temp): if temp < 0: return "Freezing" elif 0 <= temp < 10: return "Very Cold" elif 10 <= temp < 20: return "Cold" elif 20 <= temp < 30: return "Comfortable" elif 30 <= temp < 40: return "Hot" else: return "Very Hot"Pattern 2: Multiple criteria validation
def validate_password(password): conditions = [] if len(password) >= 8: conditions.append("Length OK") else: conditions.append("Too short") if any(c.isupper() for c in password): conditions.append("Has uppercase") else: conditions.append("Missing uppercase") if any(c.islower() for c in password): conditions.append("Has lowercase") else: conditions.append("Missing lowercase") if any(c.isdigit() for c in password): conditions.append("Has digit") else: conditions.append("Missing digit") special_chars = "!@#$%^&*()_+-=[]{}|;:,.<>?" if any(c in special_chars for c in password): conditions.append("Has special character") else: conditions.append("Missing special character") return conditionsUsage example
password = "MySecure123!" validation_results = validate_password(password) for result in validation_results: print(result)`Advanced Techniques
Using all() and any() Functions
The all() and any() functions provide elegant ways to evaluate multiple conditions stored in iterables.
`python
Using all() - all conditions must be True
def check_all_requirements(student_data): requirements = [ student_data['gpa'] >= 3.5, student_data['credits'] >= 120, student_data['major_credits'] >= 45, student_data['thesis_completed'], len(student_data['recommendations']) >= 2 ] return all(requirements)Using any() - at least one condition must be True
def check_scholarship_eligibility(student): criteria = [ student['gpa'] >= 3.8, student['financial_need'] and student['gpa'] >= 3.0, student['athletic_scholarship'], student['minority_status'] and student['gpa'] >= 3.2, student['first_generation'] and student['gpa'] >= 3.0 ] return any(criteria)Example usage
student = { 'gpa': 3.6, 'credits': 125, 'major_credits': 48, 'thesis_completed': True, 'recommendations': ['Dr. Smith', 'Prof. Johnson', 'Dr. Brown'], 'financial_need': True, 'athletic_scholarship': False, 'minority_status': False, 'first_generation': True }if check_all_requirements(student): print("Student meets graduation requirements")
if check_scholarship_eligibility(student):
print("Student is eligible for scholarship")
`
Conditional Expressions (Ternary Operator)
`python
Basic ternary operator
age = 20 status = "adult" if age >= 18 else "minor"Multiple conditions with ternary
score = 85 grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F"Complex ternary with multiple conditions
temperature = 25 humidity = 60 weather_comfort = ( "Perfect" if 20 <= temperature <= 25 and 40 <= humidity <= 60 else "Good" if 15 <= temperature <= 30 and 30 <= humidity <= 70 else "Poor" )Ternary in function calls
def process_data(data, validate=True): return ( validated_data(data) if validate and is_valid_format(data) else raw_data(data) if not validate else error_response("Invalid data format") )`Dictionary-Based Condition Mapping
`python
Traditional if-elif approach
def get_shipping_cost_traditional(weight, zone): if zone == "domestic": if weight <= 1: return 5.00 elif weight <= 5: return 8.00 elif weight <= 10: return 12.00 else: return 20.00 elif zone == "international": if weight <= 1: return 15.00 elif weight <= 5: return 25.00 elif weight <= 10: return 40.00 else: return 60.00Dictionary-based approach
shipping_rates = { ("domestic", "light"): 5.00, ("domestic", "medium"): 8.00, ("domestic", "heavy"): 12.00, ("domestic", "extra_heavy"): 20.00, ("international", "light"): 15.00, ("international", "medium"): 25.00, ("international", "heavy"): 40.00, ("international", "extra_heavy"): 60.00 }def get_weight_category(weight): if weight <= 1: return "light" elif weight <= 5: return "medium" elif weight <= 10: return "heavy" else: return "extra_heavy"
def get_shipping_cost_dict(weight, zone):
weight_category = get_weight_category(weight)
return shipping_rates.get((zone, weight_category), 0)
`
Best Practices
Code Organization and Readability
`python
Poor practice - hard to read and maintain
def process_order(order): if order['total'] > 0 and order['customer']['age'] >= 18 and order['customer']['verified'] and len(order['items']) > 0 and order['payment']['method'] in ['credit', 'debit', 'paypal'] and order['payment']['verified'] and order['shipping']['address'] != '' and order['shipping']['country'] in ['US', 'CA', 'UK'] and not order['customer']['blocked']: return process_payment(order) else: return reject_order(order)Good practice - readable and maintainable
def process_order(order): # Validate order basics has_items = len(order['items']) > 0 has_total = order['total'] > 0 # Validate customer customer_valid = ( order['customer']['age'] >= 18 and order['customer']['verified'] and not order['customer']['blocked'] ) # Validate payment accepted_payment_methods = ['credit', 'debit', 'paypal'] payment_valid = ( order['payment']['method'] in accepted_payment_methods and order['payment']['verified'] ) # Validate shipping supported_countries = ['US', 'CA', 'UK'] shipping_valid = ( order['shipping']['address'] != '' and order['shipping']['country'] in supported_countries ) # Process order if all conditions met if all([has_items, has_total, customer_valid, payment_valid, shipping_valid]): return process_payment(order) else: return reject_order(order)`Function-Based Condition Checking
`python
Modular approach with separate validation functions
def is_valid_email(email): return '@' in email and '.' in email and len(email) >= 5def is_strong_password(password): return ( len(password) >= 8 and any(c.isupper() for c in password) and any(c.islower() for c in password) and any(c.isdigit() for c in password) )
def is_adult(age): return age >= 18
def has_required_documents(documents): required = ['id', 'proof_of_address', 'income_statement'] return all(doc in documents for doc in required)
def validate_user_registration(user_data): validations = { 'email': is_valid_email(user_data.get('email', '')), 'password': is_strong_password(user_data.get('password', '')), 'age': is_adult(user_data.get('age', 0)), 'documents': has_required_documents(user_data.get('documents', [])) } # Check if all validations pass if all(validations.values()): return True, "Registration successful" else: failed_checks = [key for key, value in validations.items() if not value] return False, f"Failed validations: {', '.join(failed_checks)}"
Usage
user_data = { 'email': 'user@example.com', 'password': 'SecurePass123', 'age': 25, 'documents': ['id', 'proof_of_address', 'income_statement'] }is_valid, message = validate_user_registration(user_data)
print(message)
`
Common Pitfalls
Operator Precedence Mistakes
`python
Problematic code - unclear precedence
x = 5 y = 10 z = 15This might not behave as expected
if x < y and y < z or z < x: # Confusing without parentheses print("Condition met")Clear version with explicit parentheses
if (x < y and y < z) or (z < x): print("Condition met")Another common mistake
age = 25 income = 30000 credit_score = 650Problematic - mixing and/or without clear grouping
if age >= 21 and income >= 25000 or credit_score >= 700 and age >= 18: print("Approved")Clear version
if (age >= 21 and income >= 25000) or (credit_score >= 700 and age >= 18): print("Approved")`Short-Circuit Evaluation Issues
`python
Potential problem with side effects
def expensive_check(): print("Performing expensive operation...") # Simulate expensive operation import time time.sleep(1) return Truedef quick_check(): print("Quick check") return False
This will not call expensive_check due to short-circuiting
if quick_check() and expensive_check(): print("Both conditions met")If you need both functions to execute regardless
quick_result = quick_check() expensive_result = expensive_check() if quick_result and expensive_result: print("Both conditions met")`Type-Related Issues
`python
Problematic comparisons
def risky_comparison(value): # This can cause issues with different types if value == "0" or value == 0 or value == False: return "Zero-like value" return "Non-zero value"Better approach with explicit type checking
def safe_comparison(value): if isinstance(value, str) and value == "0": return "String zero" elif isinstance(value, (int, float)) and value == 0: return "Numeric zero" elif isinstance(value, bool) and value is False: return "Boolean false" else: return "Non-zero value"Testing different types
test_values = ["0", 0, False, None, "", []] for val in test_values: print(f"{val} ({type(val).__name__}): {safe_comparison(val)}")`Performance Considerations
Optimizing Condition Evaluation
`python
import time
Performance comparison example
def time_condition_check(condition_func, iterations=1000000): start_time = time.time() for _ in range(iterations): condition_func() end_time = time.time() return end_time - start_timeExample 1: Order of conditions matters
def expensive_condition(): return sum(range(100)) > 0def cheap_condition(): return True
Inefficient - expensive condition first
def inefficient_check(): return expensive_condition() and cheap_condition()Efficient - cheap condition first (short-circuit)
def efficient_check(): return cheap_condition() and expensive_condition()Example 2: Using sets for membership testing
large_list = list(range(10000)) large_set = set(large_list)def list_membership_check(): return 9999 in large_list
def set_membership_check(): return 9999 in large_set
Performance comparison
print("List membership:", time_condition_check(list_membership_check, 1000)) print("Set membership:", time_condition_check(set_membership_check, 1000))`Memory-Efficient Condition Checking
`python
Memory-efficient approaches for large datasets
def check_conditions_generator(data): """Generator-based condition checking for large datasets""" for item in data: if (item.get('active', False) and item.get('score', 0) >= 80 and item.get('category') in ['A', 'B']): yield itemdef check_conditions_list_comp(data): """List comprehension approach""" return [ item for item in data if (item.get('active', False) and item.get('score', 0) >= 80 and item.get('category') in ['A', 'B']) ]
Example usage with large dataset
large_dataset = [ {'active': True, 'score': 85, 'category': 'A'}, {'active': False, 'score': 90, 'category': 'B'}, {'active': True, 'score': 75, 'category': 'C'}, # ... thousands more items ]Memory-efficient processing
for valid_item in check_conditions_generator(large_dataset): process_item(valid_item) # Process one item at a time`Practical Examples
Example 1: E-commerce Order Processing System
`python
class OrderProcessor:
def __init__(self):
self.tax_rates = {
'CA': 0.08,
'NY': 0.07,
'TX': 0.06,
'FL': 0.05
}
self.shipping_zones = {
'domestic': ['US'],
'international': ['CA', 'UK', 'AU', 'DE']
}
def validate_order(self, order):
"""Comprehensive order validation with multiple conditions"""
validations = {}
# Customer validation
customer = order.get('customer', {})
validations['customer_age'] = customer.get('age', 0) >= 18
validations['customer_verified'] = customer.get('verified', False)
validations['customer_not_blocked'] = not customer.get('blocked', False)
# Order content validation
items = order.get('items', [])
validations['has_items'] = len(items) > 0
validations['positive_total'] = order.get('total', 0) > 0
validations['items_in_stock'] = all(
item.get('stock', 0) >= item.get('quantity', 0)
for item in items
)
# Payment validation
payment = order.get('payment', {})
accepted_methods = ['credit_card', 'debit_card', 'paypal', 'apple_pay']
validations['payment_method_valid'] = payment.get('method') in accepted_methods
validations['payment_verified'] = payment.get('verified', False)
validations['sufficient_funds'] = payment.get('available_amount', 0) >= order.get('total', 0)
# Shipping validation
shipping = order.get('shipping', {})
all_countries = self.shipping_zones['domestic'] + self.shipping_zones['international']
validations['shipping_country_supported'] = shipping.get('country') in all_countries
validations['shipping_address_complete'] = all([
shipping.get('street'),
shipping.get('city'),
shipping.get('postal_code'),
shipping.get('country')
])
return validations
def calculate_order_total(self, order):
"""Calculate total with tax and shipping based on multiple conditions"""
base_total = order.get('subtotal', 0)
shipping_country = order.get('shipping', {}).get('country')
customer_type = order.get('customer', {}).get('type', 'regular')
order_weight = sum(item.get('weight', 0) * item.get('quantity', 1)
for item in order.get('items', []))
# Calculate tax
if shipping_country == 'US':
state = order.get('shipping', {}).get('state')
tax_rate = self.tax_rates.get(state, 0.05) # Default 5%
tax_amount = base_total * tax_rate
else:
tax_amount = 0 # No tax for international orders
# Calculate shipping
if customer_type == 'premium':
shipping_cost = 0 # Free shipping for premium customers
elif base_total >= 100:
shipping_cost = 0 # Free shipping over $100
elif shipping_country in self.shipping_zones['domestic']:
if order_weight <= 2:
shipping_cost = 5.99
elif order_weight <= 10:
shipping_cost = 9.99
else:
shipping_cost = 15.99
else: # International shipping
if order_weight <= 2:
shipping_cost = 19.99
elif order_weight <= 10:
shipping_cost = 34.99
else:
shipping_cost = 49.99
# Apply discounts based on multiple conditions
discount_amount = 0
if (customer_type == 'premium' and base_total >= 50) or base_total >= 200:
discount_amount = base_total * 0.1 # 10% discount
elif order.get('coupon_code') == 'SAVE15' and base_total >= 75:
discount_amount = base_total * 0.15 # 15% discount with coupon
final_total = base_total + tax_amount + shipping_cost - discount_amount
return {
'subtotal': base_total,
'tax': tax_amount,
'shipping': shipping_cost,
'discount': discount_amount,
'total': final_total
}
def process_order(self, order):
"""Main order processing with comprehensive validation"""
validations = self.validate_order(order)
# Check if all validations pass
if all(validations.values()):
totals = self.calculate_order_total(order)
# Additional business rule checks
final_checks = {
'inventory_reserved': self.reserve_inventory(order),
'payment_processed': self.process_payment(order, totals['total']),
'shipping_scheduled': self.schedule_shipping(order)
}
if all(final_checks.values()):
return {
'status': 'success',
'order_id': self.generate_order_id(),
'totals': totals,
'estimated_delivery': self.calculate_delivery_date(order)
}
else:
failed_checks = [k for k, v in final_checks.items() if not v]
return {
'status': 'failed',
'reason': f"Processing failed: {', '.join(failed_checks)}"
}
else:
failed_validations = [k for k, v in validations.items() if not v]
return {
'status': 'invalid',
'reason': f"Validation failed: {', '.join(failed_validations)}"
}
def reserve_inventory(self, order):
# Placeholder for inventory reservation logic
return True
def process_payment(self, order, amount):
# Placeholder for payment processing logic
return True
def schedule_shipping(self, order):
# Placeholder for shipping scheduling logic
return True
def generate_order_id(self):
import uuid
return str(uuid.uuid4())[:8].upper()
def calculate_delivery_date(self, order):
from datetime import datetime, timedelta
shipping_country = order.get('shipping', {}).get('country')
if shipping_country in self.shipping_zones['domestic']:
delivery_days = 3
else:
delivery_days = 7
return (datetime.now() + timedelta(days=delivery_days)).strftime('%Y-%m-%d')
Example usage
processor = OrderProcessor()sample_order = { 'customer': { 'age': 28, 'verified': True, 'blocked': False, 'type': 'premium' }, 'items': [ {'name': 'Widget A', 'price': 29.99, 'quantity': 2, 'weight': 1.5, 'stock': 10}, {'name': 'Widget B', 'price': 19.99, 'quantity': 1, 'weight': 0.8, 'stock': 5} ], 'subtotal': 79.97, 'payment': { 'method': 'credit_card', 'verified': True, 'available_amount': 1000.00 }, 'shipping': { 'street': '123 Main St', 'city': 'Los Angeles', 'state': 'CA', 'postal_code': '90210', 'country': 'US' }, 'coupon_code': 'SAVE15' }
result = processor.process_order(sample_order)
print(f"Order processing result: {result}")
`
This comprehensive guide covers all aspects of writing multiple conditions in Python, from basic operators to advanced techniques and real-world applications. The examples demonstrate practical implementations that can be adapted for various programming scenarios, emphasizing readability, maintainability, and performance considerations.