✨ Write Clean Code
Clean code is easy to read, understand, and modify. It uses meaningful names, clear logic, and helpful comments. Writing clean code makes debugging easier and helps other developers work with your code.
# Example of clean, readable code
def calculate_monthly_payment(loan_amount: float, annual_rate: float, years: int) -> float:
"""Calculate monthly loan payment using standard formula."""
if loan_amount <= 0 or annual_rate < 0 or years <= 0:
raise ValueError("All values must be positive")
# Convert annual rate to monthly rate
monthly_rate = annual_rate / 12 / 100
# Calculate total number of payments
total_payments = years * 12
# Handle zero interest rate
if monthly_rate == 0:
return loan_amount / total_payments
# Apply standard loan payment formula
payment = loan_amount * (
monthly_rate * (1 + monthly_rate) ** total_payments
) / (
(1 + monthly_rate) ** total_payments - 1
)
return round(payment, 2)
# Clean usage with meaningful variable names
home_price = 300000
down_payment = 60000
loan_amount = home_price - down_payment
interest_rate = 4.5 # Annual percentage
loan_term = 30 # Years
monthly_payment = calculate_monthly_payment(loan_amount, interest_rate, loan_term)
print(f"Monthly payment: ${monthly_payment:,}")
🎯 Understanding Clean Code
Clean code follows principles that make it easy for humans to read and understand.
Naming Conventions
# Good naming practices
# Use descriptive names for variables
user_email = "alice@example.com"
total_price = 199.99
is_valid_user = True
max_retry_attempts = 3
# Use clear function names that describe what they do
def send_welcome_email(user_email: str) -> bool:
"""Send welcome email to new user."""
print(f"Sending welcome email to {user_email}")
return True
def calculate_discount_amount(original_price: float, discount_percent: float) -> float:
"""Calculate the discount amount in dollars."""
return original_price * (discount_percent / 100)
def is_weekend_day(day_name: str) -> bool:
"""Check if the given day is a weekend day."""
weekend_days = {'saturday', 'sunday'}
return day_name.lower() in weekend_days
# Use clear class names
class CustomerOrder:
"""Represents a customer's order with items and shipping info."""
def __init__(self, customer_id: str):
self.customer_id = customer_id
self.order_items = []
self.shipping_address = None
self.order_date = None
def add_item(self, product_name: str, quantity: int, unit_price: float):
"""Add an item to the order."""
item = {
'product_name': product_name,
'quantity': quantity,
'unit_price': unit_price,
'total_price': quantity * unit_price
}
self.order_items.append(item)
def get_order_total(self) -> float:
"""Calculate the total price of all items in the order."""
return sum(item['total_price'] for item in self.order_items)
# Example usage with clean, readable code
def process_customer_order():
"""Process a sample customer order."""
# Create new order
order = CustomerOrder("CUST-12345")
# Add items with clear names
order.add_item("Wireless Headphones", 1, 89.99)
order.add_item("Phone Case", 2, 15.99)
# Calculate totals
subtotal = order.get_order_total()
tax_rate = 8.5 # Percent
tax_amount = calculate_discount_amount(subtotal, tax_rate)
final_total = subtotal + tax_amount
print(f"Order for customer {order.customer_id}")
print(f"Subtotal: ${subtotal:.2f}")
print(f"Tax ({tax_rate}%): ${tax_amount:.2f}")
print(f"Total: ${final_total:.2f}")
process_customer_order()
Clear Logic and Control Flow
# Clean control flow and logic
def validate_user_input(username: str, password: str, email: str) -> dict:
"""Validate user registration input and return result."""
# Use early returns for validation
if not username or len(username) < 3:
return {
'valid': False,
'error': 'Username must be at least 3 characters'
}
if not password or len(password) < 8:
return {
'valid': False,
'error': 'Password must be at least 8 characters'
}
if not email or '@' not in email:
return {
'valid': False,
'error': 'Please provide a valid email address'
}
# All validations passed
return {
'valid': True,
'error': None
}
def determine_shipping_cost(weight_kg: float, distance_km: float, is_express: bool) -> float:
"""Calculate shipping cost based on weight, distance, and service type."""
# Base rate calculation
base_rate = 5.00
weight_rate = weight_kg * 0.50
distance_rate = distance_km * 0.02
total_cost = base_rate + weight_rate + distance_rate
# Apply express shipping surcharge
if is_express:
express_multiplier = 1.5
total_cost *= express_multiplier
# Apply volume discounts
if total_cost > 50:
discount_rate = 0.10 # 10% discount for orders over $50
total_cost *= (1 - discount_rate)
return round(total_cost, 2)
# Example usage
def test_clean_code_examples():
"""Test the clean code examples."""
# Test validation
validation_result = validate_user_input("alice123", "secure_password", "alice@example.com")
print(f"Validation: {validation_result}")
# Test shipping calculation
shipping_cost = determine_shipping_cost(2.5, 100, True)
print(f"Shipping cost: ${shipping_cost}")
test_clean_code_examples()
📋 Clean Code Guidelines
Aspect | Good Practice | Bad Practice |
---|---|---|
Variables | user_count , total_price | uc , tp , data |
Functions | calculate_tax() , send_email() | calc() , process() |
Constants | MAX_FILE_SIZE = 1024 | limit = 1024 |
Booleans | is_valid , has_permission | flag , check |
Classes | UserAccount , EmailService | Manager , Handler |
Comments | Explain why and business logic | Repeat what code does |
🎯 Key Takeaways
🚀 What's Next?
Learn how to optimize your Python code for better performance and efficiency.
Continue to: Optimize Performance
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.