Master Python functions, parameters, modules, and code organization for building scalable, maintainable applications
Functions are the building blocks of modular programming. They allow you to organize code into reusable, testable, and maintainable pieces. In professional development, well-designed functions are crucial for code quality and team collaboration.
Why Functions Matter:
Enterprise Applications:
Professional Context:
Large applications can have thousands of functions. Understanding how to design, organize, and document functions is essential for enterprise software development. Python's module system enables building complex applications from simple, reusable components.
Functions encapsulate code that performs a specific task and can be called multiple times with different inputs.
Basic Function Definition:
1def greet_user(name):
2 """Greet a user by name"""
3 return f"Hello, {name}! Welcome to Python!"
4
5# Function call
6message = greet_user("Alice")
7print(message) # Hello, Alice! Welcome to Python!Different Parameter Types:
1def create_profile(name, age, city="Unknown", is_active=True):
2 """
3 Create a user profile with required and optional parameters
4
5 Args:
6 name (str): User's full name (required)
7 age (int): User's age (required)
8 city (str): User's city (optional, defaults to "Unknown")
9 is_active (bool): Account status (optional, defaults to True)
10
11 Returns:
12 dict: User profile dictionary
13 """
14 return {
15 "name": name,
16 "age": age,
17 "city": city,
18 "is_active": is_active,
19 "created_at": datetime.now().isoformat()
20 }
21
22# Different ways to call the function
23profile1 = create_profile("John Doe", 30)
24profile2 = create_profile("Jane Smith", 25, "New York")
25profile3 = create_profile("Bob Wilson", 35, city="Chicago", is_active=False)Variable-Length Arguments:
1def calculate_average(*numbers):
2 """Calculate average of any number of values"""
3 if not numbers:
4 return 0
5 return sum(numbers) / len(numbers)
6
7# Usage
8avg1 = calculate_average(10, 20, 30) # 20.0
9avg2 = calculate_average(5, 15, 25, 35, 45) # 25.0
10
11def build_query(table, **conditions):
12 """Build a SQL WHERE clause from keyword arguments"""
13 where_clause = " AND ".join([f"{key} = '{value}'" for key, value in conditions.items()])
14 return f"SELECT * FROM {table} WHERE {where_clause}"
15
16# Usage
17query = build_query("users", name="John", city="Boston", active=True)
18# Result: SELECT * FROM users WHERE name = 'John' AND city = 'Boston' AND active = 'True'Type Hints (Python 3.5+):
1from typing import List, Dict, Optional, Union
2
3def process_user_data(
4 user_id: int,
5 name: str,
6 scores: List[float],
7 metadata: Optional[Dict[str, str]] = None
8) -> Dict[str, Union[str, int, float]]:
9 """
10 Process user data with type hints for better code clarity
11
12 Args:
13 user_id: Unique user identifier
14 name: User's full name
15 scores: List of numeric scores
16 metadata: Optional additional information
17
18 Returns:
19 Processed user data dictionary
20 """
21 return {
22 "id": user_id,
23 "name": name.title(),
24 "average_score": sum(scores) / len(scores) if scores else 0.0,
25 "total_scores": len(scores),
26 "metadata": metadata or {}
27 }Understanding variable scope is crucial for avoiding bugs and writing predictable code.
Local vs Global Scope:
1# Global variable
2application_name = "User Management System"
3total_users = 0
4
5def register_user(username, email):
6 """Register a new user (demonstrates local scope)"""
7 # Local variables
8 user_id = generate_user_id()
9 registration_date = datetime.now()
10
11 # Accessing global variable (read)
12 print(f"Registering user for {application_name}")
13
14 # Modifying global variable (requires global keyword)
15 global total_users
16 total_users += 1
17
18 return {
19 "id": user_id,
20 "username": username,
21 "email": email,
22 "registered": registration_date,
23 "app": application_name
24 }
25
26def generate_user_id():
27 """Generate unique user ID (local function)"""
28 import random
29 return random.randint(100000, 999999)Nonlocal Scope (Nested Functions):
1def create_counter(start=0):
2 """Create a counter function with encapsulated state"""
3 count = start
4
5 def increment(step=1):
6 nonlocal count # Modify variable in enclosing scope
7 count += step
8 return count
9
10 def decrement(step=1):
11 nonlocal count
12 count -= step
13 return count
14
15 def get_current():
16 return count
17
18 # Return dictionary of functions (closure)
19 return {
20 "increment": increment,
21 "decrement": decrement,
22 "current": get_current
23 }
24
25# Usage
26counter = create_counter(10)
27print(counter["current"]()) # 10
28print(counter["increment"](5)) # 15
29print(counter["decrement"](3)) # 12Best Practices for Scope:
1# Constants (global, uppercase)
2MAX_LOGIN_ATTEMPTS = 3
3DEFAULT_TIMEOUT = 30
4
5# Configuration (global, but organized)
6CONFIG = {
7 "database_url": "sqlite:///app.db",
8 "debug_mode": False,
9 "max_file_size": 10 * 1024 * 1024 # 10MB
10}
11
12def authenticate_user(username, password):
13 """Demonstrate proper use of global constants"""
14 attempts = 0 # Local counter
15
16 while attempts < MAX_LOGIN_ATTEMPTS: # Using global constant
17 if verify_credentials(username, password):
18 return True
19
20 attempts += 1
21 if attempts < MAX_LOGIN_ATTEMPTS:
22 print(f"Invalid credentials. {MAX_LOGIN_ATTEMPTS - attempts} attempts remaining.")
23
24 return False
25
26def verify_credentials(username, password):
27 """Mock credential verification"""
28 # In real application, this would check database
29 return username == "admin" and password == "secret123"Python offers powerful advanced function features for sophisticated programming patterns.
Lambda Functions (Anonymous Functions):
1# Basic lambda
2square = lambda x: x ** 2
3print(square(5)) # 25
4
5# Lambda with multiple parameters
6multiply = lambda x, y: x * y
7print(multiply(4, 6)) # 24
8
9# Lambdas in higher-order functions
10numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
11
12# Filter even numbers
13evens = list(filter(lambda x: x % 2 == 0, numbers)) # [2, 4, 6, 8, 10]
14
15# Square all numbers
16squares = list(map(lambda x: x ** 2, numbers)) # [1, 4, 9, 16, 25, ...]
17
18# Sort by custom criteria
19users = [("Alice", 30), ("Bob", 25), ("Charlie", 35)]
20sorted_by_age = sorted(users, key=lambda user: user[1]) # Sort by ageDecorators (Function Wrappers):
1import time
2from functools import wraps
3
4def timing_decorator(func):
5 """Decorator to measure function execution time"""
6 @wraps(func) # Preserve original function metadata
7 def wrapper(*args, **kwargs):
8 start_time = time.time()
9 result = func(*args, **kwargs)
10 end_time = time.time()
11 print(f"{func.__name__} took {end_time - start_time:.4f} seconds")
12 return result
13 return wrapper
14
15def validation_decorator(required_params):
16 """Decorator to validate function parameters"""
17 def decorator(func):
18 @wraps(func)
19 def wrapper(*args, **kwargs):
20 # Simple validation example
21 if len(args) < len(required_params):
22 raise ValueError(f"Missing required parameters: {required_params}")
23 return func(*args, **kwargs)
24 return wrapper
25 return decorator
26
27# Usage
28@timing_decorator
29@validation_decorator(["name", "age"])
30def create_user_profile(name, age, email=""):
31 """Create user profile with timing and validation"""
32 time.sleep(0.1) # Simulate work
33 return {"name": name, "age": age, "email": email}
34
35# Function now has validation and timing automatically
36profile = create_user_profile("Alice", 30, "[email protected]")Generator Functions:
1def fibonacci_generator(limit):
2 """Generate Fibonacci sequence up to limit"""
3 a, b = 0, 1
4 while a < limit:
5 yield a # Generator keyword
6 a, b = b, a + b
7
8def process_large_dataset(data_source):
9 """Process data one item at a time (memory efficient)"""
10 for item in data_source:
11 # Process item
12 processed_item = {"id": item["id"], "processed_at": time.time()}
13 yield processed_item
14
15# Usage
16fib_numbers = list(fibonacci_generator(100)) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
17
18# Memory-efficient processing
19large_dataset = [{"id": i, "data": f"item_{i}"} for i in range(1000)]
20for processed in process_large_dataset(large_dataset):
21 # Process one item at a time without loading everything into memory
22 passModules allow you to organize code across multiple files, essential for larger applications.
Creating a Module (math_utils.py):
1# math_utils.py
2"""
3Mathematical utility functions for the application
4"""
5
6import math
7
8# Module-level constants
9PI = 3.14159265359
10
11def calculate_circle_area(radius):
12 """Calculate the area of a circle"""
13 return PI * radius ** 2
14
15def calculate_distance(point1, point2):
16 """Calculate Euclidean distance between two points"""
17 x1, y1 = point1
18 x2, y2 = point2
19 return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
20
21class Calculator:
22 """Advanced calculator class"""
23
24 def __init__(self):
25 self.history = []
26
27 def add(self, a, b):
28 result = a + b
29 self.history.append(f"{a} + {b} = {result}")
30 return result
31
32# Module initialization code (runs when imported)
33if __name__ == "__main__":
34 # Test code that only runs when module is executed directly
35 print("Testing math_utils module...")
36 print(f"Circle area (r=5): {calculate_circle_area(5)}")Importing and Using Modules:
1# Different import methods
2import math_utils
3from math_utils import calculate_circle_area, PI
4from math_utils import Calculator as Calc
5import math_utils as math_util
6
7# Using imported functions
8area1 = math_utils.calculate_circle_area(10)
9area2 = calculate_circle_area(10) # Direct import
10calculator = Calc() # Aliased import
11
12# Standard library imports
13import os
14import sys
15import json
16from datetime import datetime, timedelta
17from collections import defaultdict, Counter
18
19# Third-party imports (install with pip)
20# import requests
21# import pandas as pd
22# import numpy as npPackage Structure:
1my_application/
2ā
3āāā __init__.py # Makes directory a package
4āāā config.py # Configuration settings
5āāā main.py # Main application entry point
6ā
7āāā utils/ # Utility functions package
8ā āāā __init__.py
9ā āāā math_utils.py
10ā āāā string_utils.py
11ā āāā date_utils.py
12ā
13āāā models/ # Data models package
14ā āāā __init__.py
15ā āāā user.py
16ā āāā product.py
17ā
18āāā tests/ # Test files
19 āāā __init__.py
20 āāā test_utils.py
21 āāā test_models.pyPackage __init__.py Example:
1# utils/__init__.py
2"""
3Utility functions package
4"""
5
6# Import commonly used functions to package level
7from .math_utils import calculate_circle_area, calculate_distance
8from .string_utils import format_phone_number, validate_email
9from .date_utils import format_date, days_between
10
11# Package metadata
12__version__ = "1.0.0"
13__author__ = "Your Name"
14
15# What gets imported with "from utils import *"
16__all__ = [
17 "calculate_circle_area",
18 "calculate_distance",
19 "format_phone_number",
20 "validate_email",
21 "format_date",
22 "days_between"
23]Virtual Environments and Requirements:
1# Create virtual environment
2python -m venv project_env
3
4# Activate virtual environment
5# Windows:
6project_env\Scripts\activate
7# macOS/Linux:
8source project_env/bin/activate
9
10# Install packages
11pip install requests pandas numpy
12
13# Save requirements
14pip freeze > requirements.txt
15
16# Install from requirements
17pip install -r requirements.txtBuild a comprehensive CRM system that demonstrates functions, modules, and code organization. This enterprise-grade example shows how to structure a real application with proper separation of concerns, reusable functions, and modular architecture.
1# š¢ Customer Relationship Management (CRM) System
2# Demonstrates functions, modules, and professional code organization
3
4import datetime
5import json
6from typing import List, Dict, Optional, Union
7from dataclasses import dataclass
8from functools import wraps
9
10print("=" * 80)
11print("š¢ ENTERPRISE CUSTOMER RELATIONSHIP MANAGEMENT SYSTEM")
12print("=" * 80)
13
14# ==================== DATA MODELS (Using Classes and Dataclasses) ====================
15
16@dataclass
17class Customer:
18 """Customer data model with type hints"""
19 customer_id: int
20 name: str
21 email: str
22 phone: str
23 company: str
24 status: str = "active"
25 created_at: str = None
26
27 def __post_init__(self):
28 if self.created_at is None:
29 self.created_at = datetime.datetime.now().isoformat()
30
31@dataclass
32class Interaction:
33 """Customer interaction tracking"""
34 interaction_id: int
35 customer_id: int
36 type: str # call, email, meeting, support
37 notes: str
38 timestamp: str = None
39
40 def __post_init__(self):
41 if self.timestamp is None:
42 self.timestamp = datetime.datetime.now().isoformat()
43
44# ==================== UTILITY FUNCTIONS (Module-like Organization) ====================
45
46def validation_decorator(validator_func):
47 """Decorator for input validation"""
48 def decorator(func):
49 @wraps(func)
50 def wrapper(*args, **kwargs):
51 # Validate inputs using the provided validator
52 if not validator_func(*args, **kwargs):
53 raise ValueError(f"Validation failed for {func.__name__}")
54 return func(*args, **kwargs)
55 return wrapper
56 return decorator
57
58def timing_decorator(func):
59 """Decorator to measure function execution time"""
60 @wraps(func)
61 def wrapper(*args, **kwargs):
62 start_time = datetime.datetime.now()
63 result = func(*args, **kwargs)
64 end_time = datetime.datetime.now()
65 execution_time = (end_time - start_time).total_seconds()
66 print(f"ā±ļø {func.__name__} executed in {execution_time:.4f} seconds")
67 return result
68 return wrapper
69
70# Validation functions (could be in separate validation.py module)
71def validate_email(email: str) -> bool:
72 """Basic email validation"""
73 return "@" in email and "." in email.split("@")[-1]
74
75def validate_phone(phone: str) -> bool:
76 """Basic phone validation"""
77 cleaned = ''.join(filter(str.isdigit, phone))
78 return len(cleaned) >= 10
79
80def validate_customer_data(name: str, email: str, phone: str, company: str) -> bool:
81 """Validate all customer data"""
82 return (len(name.strip()) > 0 and
83 validate_email(email) and
84 validate_phone(phone) and
85 len(company.strip()) > 0)
86
87# String formatting utilities (could be in string_utils.py module)
88def format_phone_number(phone: str) -> str:
89 """Format phone number consistently"""
90 cleaned = ''.join(filter(str.isdigit, phone))
91 if len(cleaned) == 10:
92 return f"({cleaned[:3]}) {cleaned[3:6]}-{cleaned[6:]}"
93 return phone
94
95def format_customer_name(name: str) -> str:
96 """Format customer name with proper capitalization"""
97 return ' '.join(word.capitalize() for word in name.split())
98
99# Date utilities (could be in date_utils.py module)
100def format_timestamp(timestamp_str: str) -> str:
101 """Format ISO timestamp to readable format"""
102 dt = datetime.datetime.fromisoformat(timestamp_str)
103 return dt.strftime("%Y-%m-%d %H:%M:%S")
104
105def days_since_interaction(timestamp_str: str) -> int:
106 """Calculate days since last interaction"""
107 dt = datetime.datetime.fromisoformat(timestamp_str)
108 return (datetime.datetime.now() - dt).days
109
110# ==================== CORE CRM FUNCTIONS ====================
111
112# Global data storage (in real app, this would be a database)
113customers_db: List[Customer] = []
114interactions_db: List[Interaction] = []
115next_customer_id = 1
116next_interaction_id = 1
117
118@timing_decorator
119@validation_decorator(validate_customer_data)
120def create_customer(name: str, email: str, phone: str, company: str) -> Customer:
121 """Create a new customer with validation and timing"""
122 global next_customer_id
123
124 # Format data consistently
125 formatted_name = format_customer_name(name)
126 formatted_phone = format_phone_number(phone)
127 formatted_email = email.lower().strip()
128 formatted_company = company.strip().title()
129
130 # Create customer object
131 customer = Customer(
132 customer_id=next_customer_id,
133 name=formatted_name,
134 email=formatted_email,
135 phone=formatted_phone,
136 company=formatted_company
137 )
138
139 # Add to database
140 customers_db.append(customer)
141 next_customer_id += 1
142
143 print(f"ā
Customer created: {customer.name} ({customer.email})")
144 return customer
145
146def find_customer(search_term: str) -> List[Customer]:
147 """Find customers by name, email, or company"""
148 search_lower = search_term.lower()
149 matching_customers = []
150
151 for customer in customers_db:
152 if (search_lower in customer.name.lower() or
153 search_lower in customer.email.lower() or
154 search_lower in customer.company.lower()):
155 matching_customers.append(customer)
156
157 return matching_customers
158
159def get_customer_by_id(customer_id: int) -> Optional[Customer]:
160 """Get customer by ID with type hints"""
161 for customer in customers_db:
162 if customer.customer_id == customer_id:
163 return customer
164 return None
165
166@timing_decorator
167def add_interaction(customer_id: int, interaction_type: str, notes: str) -> Optional[Interaction]:
168 """Add customer interaction with validation"""
169 global next_interaction_id
170
171 # Validate customer exists
172 customer = get_customer_by_id(customer_id)
173 if not customer:
174 print(f"ā Customer ID {customer_id} not found")
175 return None
176
177 # Validate interaction type
178 valid_types = ["call", "email", "meeting", "support", "demo"]
179 if interaction_type not in valid_types:
180 print(f"ā Invalid interaction type. Valid types: {valid_types}")
181 return None
182
183 # Create interaction
184 interaction = Interaction(
185 interaction_id=next_interaction_id,
186 customer_id=customer_id,
187 type=interaction_type,
188 notes=notes.strip()
189 )
190
191 interactions_db.append(interaction)
192 next_interaction_id += 1
193
194 print(f"ā
Interaction added for {customer.name}: {interaction_type}")
195 return interaction
196
197# ==================== REPORTING FUNCTIONS ====================
198
199def generate_customer_report(customer_id: int) -> Dict[str, Union[str, int, List]]:
200 """Generate comprehensive customer report"""
201 customer = get_customer_by_id(customer_id)
202 if not customer:
203 return {"error": "Customer not found"}
204
205 # Get customer interactions
206 customer_interactions = [i for i in interactions_db if i.customer_id == customer_id]
207
208 # Calculate metrics
209 interaction_count = len(customer_interactions)
210 interaction_types = {}
211
212 for interaction in customer_interactions:
213 interaction_types[interaction.type] = interaction_types.get(interaction.type, 0) + 1
214
215 # Find last interaction
216 last_interaction = None
217 if customer_interactions:
218 last_interaction = max(customer_interactions, key=lambda x: x.timestamp)
219
220 return {
221 "customer_id": customer.customer_id,
222 "name": customer.name,
223 "email": customer.email,
224 "company": customer.company,
225 "status": customer.status,
226 "created_at": format_timestamp(customer.created_at),
227 "total_interactions": interaction_count,
228 "interaction_breakdown": interaction_types,
229 "last_interaction": {
230 "type": last_interaction.type,
231 "date": format_timestamp(last_interaction.timestamp),
232 "days_ago": days_since_interaction(last_interaction.timestamp),
233 "notes": last_interaction.notes[:100] + "..." if len(last_interaction.notes) > 100 else last_interaction.notes
234 } if last_interaction else None
235 }
236
237def get_customer_analytics() -> Dict[str, Union[int, float, List]]:
238 """Generate system-wide analytics"""
239 total_customers = len(customers_db)
240 total_interactions = len(interactions_db)
241
242 # Customer status breakdown
243 status_breakdown = {}
244 for customer in customers_db:
245 status_breakdown[customer.status] = status_breakdown.get(customer.status, 0) + 1
246
247 # Interaction type breakdown
248 interaction_breakdown = {}
249 for interaction in interactions_db:
250 interaction_breakdown[interaction.type] = interaction_breakdown.get(interaction.type, 0) + 1
251
252 # Active customers (interacted within 30 days)
253 active_customers = 0
254 for customer in customers_db:
255 customer_interactions = [i for i in interactions_db if i.customer_id == customer.customer_id]
256 if customer_interactions:
257 last_interaction = max(customer_interactions, key=lambda x: x.timestamp)
258 if days_since_interaction(last_interaction.timestamp) <= 30:
259 active_customers += 1
260
261 return {
262 "total_customers": total_customers,
263 "total_interactions": total_interactions,
264 "average_interactions_per_customer": total_interactions / total_customers if total_customers > 0 else 0,
265 "active_customers_30_days": active_customers,
266 "customer_status_breakdown": status_breakdown,
267 "interaction_type_breakdown": interaction_breakdown
268 }
269
270# ==================== LAMBDA AND HIGHER-ORDER FUNCTIONS ====================
271
272def process_customers_with_lambda():
273 """Demonstrate lambda functions and higher-order functions"""
274 print("\nš ADVANCED CUSTOMER PROCESSING WITH LAMBDAS")
275 print("-" * 50)
276
277 # Sort customers by name
278 sorted_by_name = sorted(customers_db, key=lambda c: c.name)
279 print("Customers sorted by name:")
280 for customer in sorted_by_name:
281 print(f" ⢠{customer.name} ({customer.company})")
282
283 # Filter active customers
284 active_customers = list(filter(lambda c: c.status == "active", customers_db))
285 print(f"\nActive customers: {len(active_customers)}")
286
287 # Map customer emails to uppercase
288 email_list = list(map(lambda c: c.email.upper(), customers_db))
289 print(f"\nCustomer emails (uppercase): {email_list}")
290
291# ==================== MAIN DEMONSTRATION PROGRAM ====================
292
293def populate_sample_data():
294 """Populate system with sample data for demonstration"""
295 print("š POPULATING SAMPLE DATA")
296 print("-" * 30)
297
298 # Sample customers
299 sample_customers = [
300 ("John Smith", "[email protected]", "555-123-4567", "TechCorp Solutions"),
301 ("Sarah Johnson", "[email protected]", "555-987-6543", "Innovate Inc"),
302 ("Mike Chen", "[email protected]", "555-555-0123", "StartupXYZ"),
303 ("Emily Davis", "[email protected]", "555-444-7890", "Enterprise Corp"),
304 ("Robert Wilson", "[email protected]", "555-333-2468", "Local Business LLC")
305 ]
306
307 for name, email, phone, company in sample_customers:
308 customer = create_customer(name, email, phone, company)
309
310 # Add some interactions for each customer
311 interaction_types = ["call", "email", "meeting", "demo", "support"]
312 import random
313
314 for _ in range(random.randint(1, 4)):
315 interaction_type = random.choice(interaction_types)
316 notes = f"Sample {interaction_type} interaction with {customer.name}"
317 add_interaction(customer.customer_id, interaction_type, notes)
318
319def display_customer_list():
320 """Display all customers in formatted table"""
321 print("\nš„ CUSTOMER DIRECTORY")
322 print("-" * 40)
323
324 if not customers_db:
325 print("No customers found.")
326 return
327
328 # Table header
329 print(f"{'ID':<3} | {'Name':<20} | {'Company':<20} | {'Email':<25}")
330 print("-" * 75)
331
332 # Customer rows
333 for customer in customers_db:
334 print(f"{customer.customer_id:<3} | {customer.name:<20} | {customer.company:<20} | {customer.email:<25}")
335
336def main():
337 """Main CRM system demonstration"""
338 print("š INITIALIZING CRM SYSTEM...")
339
340 # Populate with sample data
341 populate_sample_data()
342
343 # Display customer directory
344 display_customer_list()
345
346 # Generate analytics
347 print("\nš SYSTEM ANALYTICS")
348 print("-" * 20)
349 analytics = get_customer_analytics()
350 for key, value in analytics.items():
351 if isinstance(value, dict):
352 print(f"{key.replace('_', ' ').title()}:")
353 for subkey, subvalue in value.items():
354 print(f" ⢠{subkey}: {subvalue}")
355 else:
356 print(f"{key.replace('_', ' ').title()}: {value}")
357
358 # Generate individual customer reports
359 print("\nš CUSTOMER REPORTS")
360 print("-" * 22)
361 for customer in customers_db[:3]: # Show first 3 customers
362 print(f"\n--- {customer.name} ---")
363 report = generate_customer_report(customer.customer_id)
364 print(f"Company: {report['company']}")
365 print(f"Total Interactions: {report['total_interactions']}")
366 if report['last_interaction']:
367 print(f"Last Contact: {report['last_interaction']['type']} "
368 f"({report['last_interaction']['days_ago']} days ago)")
369
370 # Demonstrate lambda functions
371 process_customers_with_lambda()
372
373 print("\nā
CRM SYSTEM DEMONSTRATION COMPLETE")
374 print("š Next: Learn data structures for more complex data handling!")
375
376# Execute the program
377if __name__ == "__main__":
378 main()š Functions and Modules Concepts Demonstrated:
1. Function Design Patterns:
@timing_decorator, @validation_decorator for cross-cutting concerns2. Parameter Handling:
name, email in create_customer()3. Scope and Organization:
customers_db, interactions_db for data storagenext_customer_id, configuration values4. Advanced Function Features:
sorted(), filter(), map() with lambdas5. Error Handling and Validation:
None or error dictionaries instead of crashing6. Professional Code Organization:
7. Real-World Applications:
8. Performance and Maintainability:
This example demonstrates how proper function design and organization enable building complex, maintainable enterprise applications with clear separation of concerns and professional code quality.
Your progress is saved in this browser, on this device only.