Welcome to the exercises for Python Boolean Applications! These exercises will help you apply the concepts from the lecture to real-world programming scenarios. You'll practice using Boolean logic to solve common programming problems and build practical applications.
Instructions: Complete each exercise in a Python environment (IDE, notebook, or interpreter). Try to solve the exercises on your own before looking at the solutions.
Create a comprehensive input validation system for a user registration form.
def validate_registration_form(username, email, password, confirm_password, age):
"""
Validate a user registration form with the following rules:
- Username: 3-20 characters, alphanumeric and underscores only
- Email: Must contain @ and at least one dot after @
- Password: At least 8 characters, must contain at least one digit and one special character
- Confirm Password: Must match password
- Age: Must be between 18 and 120
Return a tuple (is_valid, errors) where errors is a list of error messages
"""
errors = []
# Your validation code here
return (len(errors) == 0, errors)
# Test cases
# Valid registration
print(validate_registration_form(
"john_doe",
"john.doe@example.com",
"Pass123!",
"Pass123!",
25
))
# Invalid registration with multiple errors
print(validate_registration_form(
"jo",
"invalidemail",
"password",
"different",
15
))
Expected Output:
(True, []) (False, ['Username must be 3-20 characters long and contain only alphanumeric characters and underscores', 'Email must contain @ and at least one dot after @', 'Password must be at least 8 characters long and contain at least one digit and one special character', 'Passwords do not match', 'Age must be between 18 and 120'])
def validate_registration_form(username, email, password, confirm_password, age):
"""
Validate a user registration form with the following rules:
- Username: 3-20 characters, alphanumeric and underscores only
- Email: Must contain @ and at least one dot after @
- Password: At least 8 characters, must contain at least one digit and one special character
- Confirm Password: Must match password
- Age: Must be between 18 and 120
Return a tuple (is_valid, errors) where errors is a list of error messages
"""
errors = []
# Validate username
if not (3 <= len(username) <= 20 and all(c.isalnum() or c == '_' for c in username)):
errors.append("Username must be 3-20 characters long and contain only alphanumeric characters and underscores")
# Validate email
if not ('@' in email and '.' in email.split('@')[-1]):
errors.append("Email must contain @ and at least one dot after @")
# Validate password
if not (len(password) >= 8 and
any(c.isdigit() for c in password) and
any(not c.isalnum() for c in password)):
errors.append("Password must be at least 8 characters long and contain at least one digit and one special character")
# Validate password confirmation
if password != confirm_password:
errors.append("Passwords do not match")
# Validate age
if not (18 <= age <= 120):
errors.append("Age must be between 18 and 120")
return (len(errors) == 0, errors)
# Test cases
# Valid registration
print(validate_registration_form(
"john_doe",
"john.doe@example.com",
"Pass123!",
"Pass123!",
25
))
# Invalid registration with multiple errors
print(validate_registration_form(
"jo",
"invalidemail",
"password",
"different",
15
))
Implement a more advanced feature flag system with user group targeting.
class User:
def __init__(self, user_id, name, country, is_premium=False, joined_date=None):
self.user_id = user_id
self.name = name
self.country = country
self.is_premium = is_premium
self.joined_date = joined_date # A string like "2023-01-15"
self.groups = []
def add_to_group(self, group):
if group not in self.groups:
self.groups.append(group)
def is_in_group(self, group):
return group in self.groups
class AdvancedFeatureFlags:
def __init__(self):
self.features = {}
self.country_overrides = {}
self.group_overrides = {}
self.user_overrides = {}
def add_feature(self, feature_name, default_enabled=False):
"""Add a new feature flag with default value."""
# Your code here
pass
def is_enabled(self, feature_name, user):
"""
Check if a feature is enabled for a specific user.
The precedence order is:
1. User-specific override
2. Group override (if user is in the group)
3. Country override
4. Default feature value
"""
# Your code here
pass
def enable_for_user(self, feature_name, user_id):
"""Enable a feature for a specific user."""
# Your code here
pass
def disable_for_user(self, feature_name, user_id):
"""Disable a feature for a specific user."""
# Your code here
pass
def enable_for_group(self, feature_name, group):
"""Enable a feature for a specific group."""
# Your code here
pass
def enable_for_country(self, feature_name, country):
"""Enable a feature for a specific country."""
# Your code here
pass
# Test your implementation
# Create feature flag system
feature_flags = AdvancedFeatureFlags()
feature_flags.add_feature("dark_mode", default_enabled=False)
feature_flags.add_feature("beta_dashboard", default_enabled=False)
feature_flags.add_feature("notifications", default_enabled=True)
# Set up targeting rules
feature_flags.enable_for_country("dark_mode", "Canada")
feature_flags.enable_for_group("beta_dashboard", "testers")
# Create test users
alice = User("u123", "Alice", "USA", is_premium=True)
alice.add_to_group("testers")
bob = User("u456", "Bob", "Canada", is_premium=False)
charlie = User("u789", "Charlie", "UK", is_premium=True)
charlie.add_to_group("developers")
# Enable features for specific users
feature_flags.enable_for_user("dark_mode", "u789") # Enable for Charlie
# Test feature availability
print(f"Dark mode for Alice: {feature_flags.is_enabled('dark_mode', alice)}")
print(f"Dark mode for Bob: {feature_flags.is_enabled('dark_mode', bob)}")
print(f"Dark mode for Charlie: {feature_flags.is_enabled('dark_mode', charlie)}")
print(f"Beta dashboard for Alice: {feature_flags.is_enabled('beta_dashboard', alice)}")
print(f"Beta dashboard for Bob: {feature_flags.is_enabled('beta_dashboard', bob)}")
print(f"Notifications for all users: {feature_flags.is_enabled('notifications', alice)}")
Expected Output:
Dark mode for Alice: False Dark mode for Bob: True Dark mode for Charlie: True Beta dashboard for Alice: True Beta dashboard for Bob: False Notifications for all users: True
class User:
def __init__(self, user_id, name, country, is_premium=False, joined_date=None):
self.user_id = user_id
self.name = name
self.country = country
self.is_premium = is_premium
self.joined_date = joined_date # A string like "2023-01-15"
self.groups = []
def add_to_group(self, group):
if group not in self.groups:
self.groups.append(group)
def is_in_group(self, group):
return group in self.groups
class AdvancedFeatureFlags:
def __init__(self):
self.features = {}
self.country_overrides = {}
self.group_overrides = {}
self.user_overrides = {}
def add_feature(self, feature_name, default_enabled=False):
"""Add a new feature flag with default value."""
self.features[feature_name] = default_enabled
def is_enabled(self, feature_name, user):
"""
Check if a feature is enabled for a specific user.
The precedence order is:
1. User-specific override
2. Group override (if user is in the group)
3. Country override
4. Default feature value
"""
# Check if feature exists
if feature_name not in self.features:
return False
# 1. Check user-specific override
if feature_name in self.user_overrides and user.user_id in self.user_overrides[feature_name]:
return self.user_overrides[feature_name][user.user_id]
# 2. Check group overrides
if feature_name in self.group_overrides:
for group in user.groups:
if group in self.group_overrides[feature_name] and self.group_overrides[feature_name][group]:
return True
# 3. Check country override
if feature_name in self.country_overrides and user.country in self.country_overrides[feature_name]:
return self.country_overrides[feature_name][user.country]
# 4. Fall back to default value
return self.features[feature_name]
def enable_for_user(self, feature_name, user_id):
"""Enable a feature for a specific user."""
if feature_name not in self.user_overrides:
self.user_overrides[feature_name] = {}
self.user_overrides[feature_name][user_id] = True
def disable_for_user(self, feature_name, user_id):
"""Disable a feature for a specific user."""
if feature_name not in self.user_overrides:
self.user_overrides[feature_name] = {}
self.user_overrides[feature_name][user_id] = False
def enable_for_group(self, feature_name, group):
"""Enable a feature for a specific group."""
if feature_name not in self.group_overrides:
self.group_overrides[feature_name] = {}
self.group_overrides[feature_name][group] = True
def enable_for_country(self, feature_name, country):
"""Enable a feature for a specific country."""
if feature_name not in self.country_overrides:
self.country_overrides[feature_name] = {}
self.country_overrides[feature_name][country] = True
# Test your implementation
# Create feature flag system
feature_flags = AdvancedFeatureFlags()
feature_flags.add_feature("dark_mode", default_enabled=False)
feature_flags.add_feature("beta_dashboard", default_enabled=False)
feature_flags.add_feature("notifications", default_enabled=True)
# Set up targeting rules
feature_flags.enable_for_country("dark_mode", "Canada")
feature_flags.enable_for_group("beta_dashboard", "testers")
# Create test users
alice = User("u123", "Alice", "USA", is_premium=True)
alice.add_to_group("testers")
bob = User("u456", "Bob", "Canada", is_premium=False)
charlie = User("u789", "Charlie", "UK", is_premium=True)
charlie.add_to_group("developers")
# Enable features for specific users
feature_flags.enable_for_user("dark_mode", "u789") # Enable for Charlie
# Test feature availability
print(f"Dark mode for Alice: {feature_flags.is_enabled('dark_mode', alice)}")
print(f"Dark mode for Bob: {feature_flags.is_enabled('dark_mode', bob)}")
print(f"Dark mode for Charlie: {feature_flags.is_enabled('dark_mode', charlie)}")
print(f"Beta dashboard for Alice: {feature_flags.is_enabled('beta_dashboard', alice)}")
print(f"Beta dashboard for Bob: {feature_flags.is_enabled('beta_dashboard', bob)}")
print(f"Notifications for all users: {feature_flags.is_enabled('notifications', alice)}")
Implement custom Boolean behavior for domain-specific classes.
class ShoppingCart:
"""
A shopping cart that can be evaluated in Boolean context.
An empty cart is considered False, a cart with items is True.
"""
def __init__(self):
self.items = []
# Implement __bool__ method
# Your code here
def add_item(self, item, price, quantity=1):
self.items.append({"item": item, "price": price, "quantity": quantity})
def remove_item(self, item):
for i, cart_item in enumerate(self.items):
if cart_item["item"] == item:
self.items.pop(i)
return True
return False
def get_total(self):
return sum(item["price"] * item["quantity"] for item in self.items)
class ValidationResult:
"""
A validation result that can be evaluated in Boolean context.
Valid is True, invalid is False. Stores error messages.
"""
def __init__(self, is_valid=True, errors=None):
self.is_valid = is_valid
self.errors = errors or []
# Implement __bool__ method
# Your code here
def add_error(self, error):
self.errors.append(error)
self.is_valid = False
def get_errors(self):
return self.errors
# Test your implementations
cart = ShoppingCart()
# Test empty cart (should be False)
if cart:
print("Cart has items")
else:
print("Cart is empty")
# Add some items
cart.add_item("Laptop", 1000)
cart.add_item("Mouse", 25, 2)
# Test cart with items (should be True)
if cart:
print(f"Cart has items, total: ${cart.get_total()}")
else:
print("Cart is empty")
# Test ValidationResult
validation = ValidationResult()
# Test valid result (should be True)
if validation:
print("Validation passed")
else:
print("Validation failed")
# Add some errors
validation.add_error("Username is required")
validation.add_error("Password is too short")
# Test invalid result (should be False)
if validation:
print("Validation passed")
else:
print(f"Validation failed with errors: {validation.get_errors()}")
Expected Output:
Cart is empty Cart has items, total: $1050 Validation passed Validation failed with errors: ['Username is required', 'Password is too short']
class ShoppingCart:
"""
A shopping cart that can be evaluated in Boolean context.
An empty cart is considered False, a cart with items is True.
"""
def __init__(self):
self.items = []
def __bool__(self):
"""Return True if the cart has items, False otherwise"""
return len(self.items) > 0
def add_item(self, item, price, quantity=1):
self.items.append({"item": item, "price": price, "quantity": quantity})
def remove_item(self, item):
for i, cart_item in enumerate(self.items):
if cart_item["item"] == item:
self.items.pop(i)
return True
return False
def get_total(self):
return sum(item["price"] * item["quantity"] for item in self.items)
class ValidationResult:
"""
A validation result that can be evaluated in Boolean context.
Valid is True, invalid is False. Stores error messages.
"""
def __init__(self, is_valid=True, errors=None):
self.is_valid = is_valid
self.errors = errors or []
def __bool__(self):
"""Return True if validation passed, False otherwise"""
return self.is_valid
def add_error(self, error):
self.errors.append(error)
self.is_valid = False
def get_errors(self):
return self.errors
# Test your implementations
cart = ShoppingCart()
# Test empty cart (should be False)
if cart:
print("Cart has items")
else:
print("Cart is empty")
# Add some items
cart.add_item("Laptop", 1000)
cart.add_item("Mouse", 25, 2)
# Test cart with items (should be True)
if cart:
print(f"Cart has items, total: ${cart.get_total()}")
else:
print("Cart is empty")
# Test ValidationResult
validation = ValidationResult()
# Test valid result (should be True)
if validation:
print("Validation passed")
else:
print("Validation failed")
# Add some errors
validation.add_error("Username is required")
validation.add_error("Password is too short")
# Test invalid result (should be False)
if validation:
print("Validation passed")
else:
print(f"Validation failed with errors: {validation.get_errors()}")
Implement a role-based access control (RBAC) system for a web application.
class User:
def __init__(self, username, email):
self.username = username
self.email = email
self.roles = []
self.is_active = True
self.is_authenticated = False
def add_role(self, role):
if role not in self.roles:
self.roles.append(role)
def has_role(self, role):
return role in self.roles
class Permission:
def __init__(self, name, description=""):
self.name = name
self.description = description
class Role:
def __init__(self, name, description=""):
self.name = name
self.description = description
self.permissions = []
def add_permission(self, permission):
if permission not in self.permissions:
self.permissions.append(permission)
def has_permission(self, permission_name):
return any(p.name == permission_name for p in self.permissions)
class PermissionSystem:
def __init__(self):
self.roles = {}
self.permissions = {}
def add_permission(self, name, description=""):
"""Add a new permission to the system."""
# Your code here
pass
def add_role(self, name, description=""):
"""Add a new role to the system."""
# Your code here
pass
def assign_permission_to_role(self, permission_name, role_name):
"""Assign a permission to a role."""
# Your code here
pass
def user_has_permission(self, user, permission_name):
"""
Check if a user has a specific permission through any of their roles.
Returns:
- False if user is not active or not authenticated
- False if permission doesn't exist
- True if user has any role with the permission
- False otherwise
"""
# Your code here
pass
# Create your permission system
permission_system = PermissionSystem()
# Add permissions
permission_system.add_permission("create_post", "Can create new posts")
permission_system.add_permission("edit_post", "Can edit existing posts")
permission_system.add_permission("delete_post", "Can delete posts")
permission_system.add_permission("admin_panel", "Can access admin panel")
# Add roles
permission_system.add_role("user", "Regular user")
permission_system.add_role("moderator", "Content moderator")
permission_system.add_role("admin", "Administrator")
# Assign permissions to roles
permission_system.assign_permission_to_role("create_post", "user")
permission_system.assign_permission_to_role("create_post", "moderator")
permission_system.assign_permission_to_role("edit_post", "moderator")
permission_system.assign_permission_to_role("delete_post", "moderator")
permission_system.assign_permission_to_role("create_post", "admin")
permission_system.assign_permission_to_role("edit_post", "admin")
permission_system.assign_permission_to_role("delete_post", "admin")
permission_system.assign_permission_to_role("admin_panel", "admin")
# Create test users
alice = User("alice", "alice@example.com")
alice.is_authenticated = True
alice.add_role(permission_system.roles["admin"])
bob = User("bob", "bob@example.com")
bob.is_authenticated = True
bob.add_role(permission_system.roles["moderator"])
charlie = User("charlie", "charlie@example.com")
charlie.is_authenticated = True
charlie.add_role(permission_system.roles["user"])
dave = User("dave", "dave@example.com")
dave.is_authenticated = False # Not authenticated
dave.add_role(permission_system.roles["user"])
# Test permissions
print(f"Alice can access admin panel: {permission_system.user_has_permission(alice, 'admin_panel')}")
print(f"Bob can delete posts: {permission_system.user_has_permission(bob, 'delete_post')}")
print(f"Bob can access admin panel: {permission_system.user_has_permission(bob, 'admin_panel')}")
print(f"Charlie can create posts: {permission_system.user_has_permission(charlie, 'create_post')}")
print(f"Charlie can edit posts: {permission_system.user_has_permission(charlie, 'edit_post')}")
print(f"Dave can create posts: {permission_system.user_has_permission(dave, 'create_post')}") # Should be False (not authenticated)
Expected Output:
Alice can access admin panel: True Bob can delete posts: True Bob can access admin panel: False Charlie can create posts: True Charlie can edit posts: False Dave can create posts: False
class User:
def __init__(self, username, email):
self.username = username
self.email = email
self.roles = []
self.is_active = True
self.is_authenticated = False
def add_role(self, role):
if role not in self.roles:
self.roles.append(role)
def has_role(self, role):
return role in self.roles
class Permission:
def __init__(self, name, description=""):
self.name = name
self.description = description
class Role:
def __init__(self, name, description=""):
self.name = name
self.description = description
self.permissions = []
def add_permission(self, permission):
if permission not in self.permissions:
self.permissions.append(permission)
def has_permission(self, permission_name):
return any(p.name == permission_name for p in self.permissions)
class PermissionSystem:
def __init__(self):
self.roles = {}
self.permissions = {}
def add_permission(self, name, description=""):
"""Add a new permission to the system."""
permission = Permission(name, description)
self.permissions[name] = permission
return permission
def add_role(self, name, description=""):
"""Add a new role to the system."""
role = Role(name, description)
self.roles[name] = role
return role
def assign_permission_to_role(self, permission_name, role_name):
"""Assign a permission to a role."""
if permission_name in self.permissions and role_name in self.roles:
permission = self.permissions[permission_name]
role = self.roles[role_name]
role.add_permission(permission)
return True
return False
def user_has_permission(self, user, permission_name):
"""
Check if a user has a specific permission through any of their roles.
Returns:
- False if user is not active or not authenticated
- False if permission doesn't exist
- True if user has any role with the permission
- False otherwise
"""
# Check if user is active and authenticated
if not (user.is_active and user.is_authenticated):
return False
# Check if permission exists
if permission_name not in self.permissions:
return False
# Check if user has any role with the permission
for role in user.roles:
if role.has_permission(permission_name):
return True
return False
# Create your permission system
permission_system = PermissionSystem()
# Add permissions
permission_system.add_permission("create_post", "Can create new posts")
permission_system.add_permission("edit_post", "Can edit existing posts")
permission_system.add_permission("delete_post", "Can delete posts")
permission_system.add_permission("admin_panel", "Can access admin panel")
# Add roles
permission_system.add_role("user", "Regular user")
permission_system.add_role("moderator", "Content moderator")
permission_system.add_role("admin", "Administrator")
# Assign permissions to roles
permission_system.assign_permission_to_role("create_post", "user")
permission_system.assign_permission_to_role("create_post", "moderator")
permission_system.assign_permission_to_role("edit_post", "moderator")
permission_system.assign_permission_to_role("delete_post", "moderator")
permission_system.assign_permission_to_role("create_post", "admin")
permission_system.assign_permission_to_role("edit_post", "admin")
permission_system.assign_permission_to_role("delete_post", "admin")
permission_system.assign_permission_to_role("admin_panel", "admin")
# Create test users
alice = User("alice", "alice@example.com")
alice.is_authenticated = True
alice.add_role(permission_system.roles["admin"])
bob = User("bob", "bob@example.com")
bob.is_authenticated = True
bob.add_role(permission_system.roles["moderator"])
charlie = User("charlie", "charlie@example.com")
charlie.is_authenticated = True
charlie.add_role(permission_system.roles["user"])
dave = User("dave", "dave@example.com")
dave.is_authenticated = False # Not authenticated
dave.add_role(permission_system.roles["user"])
# Test permissions
print(f"Alice can access admin panel: {permission_system.user_has_permission(alice, 'admin_panel')}")
print(f"Bob can delete posts: {permission_system.user_has_permission(bob, 'delete_post')}")
print(f"Bob can access admin panel: {permission_system.user_has_permission(bob, 'admin_panel')}")
print(f"Charlie can create posts: {permission_system.user_has_permission(charlie, 'create_post')}")
print(f"Charlie can edit posts: {permission_system.user_has_permission(charlie, 'edit_post')}")
print(f"Dave can create posts: {permission_system.user_has_permission(dave, 'create_post')}") # Should be False (not authenticated)
Implement a smart home automation system that uses Boolean logic to control devices based on conditions and rules.
class Device:
def __init__(self, name, device_type):
self.name = name
self.type = device_type
self.is_on = False
self.settings = {}
def turn_on(self):
self.is_on = True
print(f"{self.name} ({self.type}) turned ON")
def turn_off(self):
self.is_on = False
print(f"{self.name} ({self.type}) turned OFF")
def update_setting(self, setting, value):
self.settings[setting] = value
print(f"{self.name} ({self.type}) {setting} set to {value}")
def get_state_description(self):
state = "ON" if self.is_on else "OFF"
settings_str = ", ".join(f"{k}: {v}" for k, v in self.settings.items())
return f"{self.name} ({self.type}) is {state}" + (f" with {settings_str}" if settings_str else "")
class Sensor:
def __init__(self, name, sensor_type):
self.name = name
self.type = sensor_type
self.value = 0
def update_value(self, value):
self.value = value
print(f"{self.name} ({self.type}) reading: {value}")
def get_reading(self):
return self.value
class SmartHome:
def __init__(self, name):
self.name = name
self.devices = {}
self.sensors = {}
self.rules = []
self.is_running = False
def add_device(self, device):
self.devices[device.name] = device
def add_sensor(self, sensor):
self.sensors[sensor.name] = sensor
def add_rule(self, rule):
self.rules.append(rule)
def evaluate_rules(self):
"""Evaluate all rules and take actions."""
# Your code here
pass
def start(self):
"""Start the smart home system."""
# Your code here
pass
def stop(self):
"""Stop the smart home system."""
# Your code here
pass
def get_status(self):
"""Return the status of all devices and sensors."""
# Your code here
pass
class Rule:
def __init__(self, name, condition_func, action_func):
self.name = name
self.condition = condition_func
self.action = action_func
self.is_active = True
def evaluate(self, smart_home):
"""Evaluate the rule and take action if the condition is met."""
# Your code here
pass
# Create your smart home system
smart_home = SmartHome("My Smart Home")
# Add devices
smart_home.add_device(Device("Living Room Light", "light"))
smart_home.add_device(Device("Bedroom Light", "light"))
smart_home.add_device(Device("Air Conditioner", "climate"))
smart_home.add_device(Device("Heater", "climate"))
# Add sensors
smart_home.add_sensor(Sensor("Living Room Temperature", "temperature"))
smart_home.add_sensor(Sensor("Outside Temperature", "temperature"))
smart_home.add_sensor(Sensor("Living Room Motion", "motion"))
smart_home.add_sensor(Sensor("Light Level", "light"))
# Define rule conditions and actions
def temperature_too_high(home):
"""Condition: Indoor temperature is above 25°C and AC is off."""
return home.sensors["Living Room Temperature"].get_reading() > 25 and not home.devices["Air Conditioner"].is_on
def turn_on_ac(home):
"""Action: Turn on the AC and set it to 22°C."""
home.devices["Air Conditioner"].turn_on()
home.devices["Air Conditioner"].update_setting("temperature", 22)
def temperature_too_low(home):
"""Condition: Indoor temperature is below 18°C and heater is off."""
return home.sensors["Living Room Temperature"].get_reading() < 18 and not home.devices["Heater"].is_on
def turn_on_heater(home):
"""Action: Turn on the heater."""
home.devices["Heater"].turn_on()
def motion_detected_dark(home):
"""Condition: Motion detected in living room, light level is low, and lights are off."""
return (home.sensors["Living Room Motion"].get_reading() > 0 and
home.sensors["Light Level"].get_reading() < 20 and
not home.devices["Living Room Light"].is_on)
def turn_on_lights(home):
"""Action: Turn on the living room lights."""
home.devices["Living Room Light"].turn_on()
# Add rules to the system
smart_home.add_rule(Rule("AC Rule", temperature_too_high, turn_on_ac))
smart_home.add_rule(Rule("Heater Rule", temperature_too_low, turn_on_heater))
smart_home.add_rule(Rule("Automatic Lights", motion_detected_dark, turn_on_lights))
# Start the system
smart_home.start()
# Simulate sensor readings
smart_home.sensors["Living Room Temperature"].update_value(27)
smart_home.sensors["Outside Temperature"].update_value(30)
smart_home.sensors["Light Level"].update_value(10)
smart_home.sensors["Living Room Motion"].update_value(1)
# Evaluate rules based on these readings
smart_home.evaluate_rules()
# Check status
print("\nCurrent Status:")
print(smart_home.get_status())
# Change conditions
smart_home.sensors["Living Room Temperature"].update_value(16)
smart_home.evaluate_rules()
# Stop the system
smart_home.stop()
Expected Output (will vary slightly):
Smart Home "My Smart Home" started. Living Room Temperature (temperature) reading: 27 Outside Temperature (temperature) reading: 30 Light Level (light) reading: 10 Living Room Motion (motion) reading: 1 Evaluating rule: AC Rule Condition met for rule: AC Rule Air Conditioner (climate) turned ON Air Conditioner (climate) temperature set to 22 Evaluating rule: Heater Rule Evaluating rule: Automatic Lights Condition met for rule: Automatic Lights Living Room Light (light) turned ON Current Status: Devices: - Living Room Light (light) is ON - Bedroom Light (light) is OFF - Air Conditioner (climate) is ON with temperature: 22 - Heater (climate) is OFF Sensors: - Living Room Temperature (temperature): 27 - Outside Temperature (temperature): 30 - Living Room Motion (motion): 1 - Light Level (light): 10 Living Room Temperature (temperature) reading: 16 Evaluating rule: AC Rule Evaluating rule: Heater Rule Condition met for rule: Heater Rule Heater (climate) turned ON Evaluating rule: Automatic Lights Smart Home "My Smart Home" stopped.
class Device:
def __init__(self, name, device_type):
self.name = name
self.type = device_type
self.is_on = False
self.settings = {}
def turn_on(self):
self.is_on = True
print(f"{self.name} ({self.type}) turned ON")
def turn_off(self):
self.is_on = False
print(f"{self.name} ({self.type}) turned OFF")
def update_setting(self, setting, value):
self.settings[setting] = value
print(f"{self.name} ({self.type}) {setting} set to {value}")
def get_state_description(self):
state = "ON" if self.is_on else "OFF"
settings_str = ", ".join(f"{k}: {v}" for k, v in self.settings.items())
return f"{self.name} ({self.type}) is {state}" + (f" with {settings_str}" if settings_str else "")
class Sensor:
def __init__(self, name, sensor_type):
self.name = name
self.type = sensor_type
self.value = 0
def update_value(self, value):
self.value = value
print(f"{self.name} ({self.type}) reading: {value}")
def get_reading(self):
return self.value
class SmartHome:
def __init__(self, name):
self.name = name
self.devices = {}
self.sensors = {}
self.rules = []
self.is_running = False
def add_device(self, device):
self.devices[device.name] = device
def add_sensor(self, sensor):
self.sensors[sensor.name] = sensor
def add_rule(self, rule):
self.rules.append(rule)
def evaluate_rules(self):
"""Evaluate all rules and take actions."""
print(f"Evaluating rules...")
for rule in self.rules:
if self.is_running and rule.is_active:
rule.evaluate(self)
def start(self):
"""Start the smart home system."""
self.is_running = True
print(f'Smart Home "{self.name}" started.')
def stop(self):
"""Stop the smart home system."""
self.is_running = False
print(f'Smart Home "{self.name}" stopped.')
def get_status(self):
"""Return the status of all devices and sensors."""
status = "Devices:\n"
for name, device in self.devices.items():
status += f"- {device.get_state_description()}\n"
status += "Sensors:\n"
for name, sensor in self.sensors.items():
status += f"- {sensor.name} ({sensor.type}): {sensor.get_reading()}\n"
return status.strip()
class Rule:
def __init__(self, name, condition_func, action_func):
self.name = name
self.condition = condition_func
self.action = action_func
self.is_active = True
def evaluate(self, smart_home):
"""Evaluate the rule and take action if the condition is met."""
print(f"Evaluating rule: {self.name}")
if self.condition(smart_home):
print(f"Condition met for rule: {self.name}")
self.action(smart_home)
return
# Create your smart home system
smart_home = SmartHome("My Smart Home")
# Add devices
smart_home.add_device(Device("Living Room Light", "light"))
smart_home.add_device(Device("Bedroom Light", "light"))
smart_home.add_device(Device("Air Conditioner", "climate"))
smart_home.add_device(Device("Heater", "climate"))
# Add sensors
smart_home.add_sensor(Sensor("Living Room Temperature", "temperature"))
smart_home.add_sensor(Sensor("Outside Temperature", "temperature"))
smart_home.add_sensor(Sensor("Living Room Motion", "motion"))
smart_home.add_sensor(Sensor("Light Level", "light"))
# Define rule conditions and actions
def temperature_too_high(home):
"""Condition: Indoor temperature is above 25°C and AC is off."""
return home.sensors["Living Room Temperature"].get_reading() > 25 and not home.devices["Air Conditioner"].is_on
def turn_on_ac(home):
"""Action: Turn on the AC and set it to 22°C."""
home.devices["Air Conditioner"].turn_on()
home.devices["Air Conditioner"].update_setting("temperature", 22)
def temperature_too_low(home):
"""Condition: Indoor temperature is below 18°C and heater is off."""
return home.sensors["Living Room Temperature"].get_reading() < 18 and not home.devices["Heater"].is_on
def turn_on_heater(home):
"""Action: Turn on the heater."""
home.devices["Heater"].turn_on()
def motion_detected_dark(home):
"""Condition: Motion detected in living room, light level is low, and lights are off."""
return (home.sensors["Living Room Motion"].get_reading() > 0 and
home.sensors["Light Level"].get_reading() < 20 and
not home.devices["Living Room Light"].is_on)
def turn_on_lights(home):
"""Action: Turn on the living room lights."""
home.devices["Living Room Light"].turn_on()
# Add rules to the system
smart_home.add_rule(Rule("AC Rule", temperature_too_high, turn_on_ac))
smart_home.add_rule(Rule("Heater Rule", temperature_too_low, turn_on_heater))
smart_home.add_rule(Rule("Automatic Lights", motion_detected_dark, turn_on_lights))
# Start the system
smart_home.start()
# Simulate sensor readings
smart_home.sensors["Living Room Temperature"].update_value(27)
smart_home.sensors["Outside Temperature"].update_value(30)
smart_home.sensors["Light Level"].update_value(10)
smart_home.sensors["Living Room Motion"].update_value(1)
# Evaluate rules based on these readings
smart_home.evaluate_rules()
# Check status
print("\nCurrent Status:")
print(smart_home.get_status())
# Change conditions
smart_home.sensors["Living Room Temperature"].update_value(16)
smart_home.evaluate_rules()
# Stop the system
smart_home.stop()
Congratulations on completing these advanced exercises on Boolean applications in Python! You've practiced:
These exercises demonstrate how Boolean logic forms the foundation of many real-world applications and systems. By mastering these concepts, you'll be able to build more robust and sophisticated software.
What Next? Continue exploring Python by applying these Boolean concepts to your own projects. Consider combining them with other Python features like generators, decorators, or context managers to build even more powerful applications.
Return to Boolean Basics Lecture | Return to Boolean Applications Lecture
© 2025 RMdelapaz All rights reserved.