Advanced Code Example — Functions and Abstraction#

This example demonstrates a multi-function analytics pipeline where each function handles one responsibility and functions are composed together to produce a complete business report.


Business Scenario#

You are building a customer analytics pipeline for a retail company. The pipeline must be modular, reusable, and easy to update when business rules change. Each step of the analysis is encapsulated in its own function.


Code#

# ══════════════════════════════════════════════════════════
#  CUSTOMER ANALYTICS PIPELINE — Function-Driven Design
# ══════════════════════════════════════════════════════════

# ── Tier Classification ──────────────────────────────────────────────
def classify_tier(total_spent: float, purchase_count: int) -> str:
    """Classify customer into loyalty tier based on spend and frequency."""
    if total_spent >= 1500 and purchase_count >= 12:
        return 'Platinum+'
    elif total_spent >= 1000 and purchase_count >= 8:
        return 'Platinum'
    elif total_spent >= 500 or purchase_count >= 5:
        return 'Gold'
    elif total_spent >= 200:
        return 'Silver'
    return 'Standard'


# ── Purchase Metrics ─────────────────────────────────────────────────
def compute_metrics(purchase_list: list) -> dict:
    """Return a dictionary of key purchase metrics."""
    if not purchase_list:
        return {'total': 0.0, 'average': 0.0, 'max': 0.0, 'count': 0}
    total = sum(purchase_list)
    return {
        'total':   round(total, 2),
        'average': round(total / len(purchase_list), 2),
        'max':     round(max(purchase_list), 2),
        'count':   len(purchase_list)
    }


# ── Discount Calculation ─────────────────────────────────────────────
def calculate_discount(tier: str, is_loyalty_member: bool) -> float:
    """Return shipping discount rate based on tier and membership."""
    base_discounts = {
        'Platinum+': 0.25,
        'Platinum':  0.20,
        'Gold':      0.12,
        'Silver':    0.07,
        'Standard':  0.00
    }
    discount = base_discounts.get(tier, 0.00)
    if is_loyalty_member and discount < 0.25:
        discount = min(discount + 0.03, 0.25)  # loyalty bonus, capped at 25%
    return discount


# ── Customer Report Builder ──────────────────────────────────────────
def build_customer_report(customer: dict) -> dict:
    """Compose all analytics functions to build a full customer report."""
    metrics  = compute_metrics(customer['purchases'])
    tier     = classify_tier(metrics['total'], metrics['count'])
    discount = calculate_discount(tier, customer.get('is_loyalty_member', False))

    return {
        'name':     customer['name'],
        'region':   customer['region'],
        'tier':     tier,
        'metrics':  metrics,
        'discount': discount
    }


# ── Report Printer ────────────────────────────────────────────────────
def print_report(report: dict) -> None:
    """Display a formatted customer report."""
    m = report['metrics']
    print(f"  {report['name']:<20} | {report['region']:<12} | {report['tier']:<10}")
    print(f"    Total: ${m['total']:>8,.2f}  |  Avg: ${m['average']:>7,.2f}"
          f"  |  Max: ${m['max']:>7,.2f}  |  Purchases: {m['count']}")
    print(f"    Shipping Discount: {report['discount']*100:.0f}%")
    print()


# ══════════════════════════════════════════════════════════
#  MAIN PIPELINE — compose the functions
# ══════════════════════════════════════════════════════════
customers = [
    {'name': 'Alice Johnson', 'region': 'Northwest', 'is_loyalty_member': True,
     'purchases': [250.50, 180.75, 420.25, 310.00, 320.00, 420.00, 510.00, 450.00, 360.00, 290.00, 415.00, 230.25]},
    {'name': 'Bob Martinez',  'region': 'Southwest', 'is_loyalty_member': False,
     'purchases': [95.80, 215.25, 110.00]},
    {'name': 'Carol Chen',    'region': 'Northwest', 'is_loyalty_member': True,
     'purchases': [300.00, 290.75, 300.00, 410.00, 350.00]},
    {'name': 'David Kim',     'region': 'Southeast', 'is_loyalty_member': False,
     'purchases': [45.00, 60.00]},
]

print("=" * 60)
print("  CUSTOMER ANALYTICS PIPELINE OUTPUT")
print("=" * 60 + "\n")

reports = [build_customer_report(c) for c in customers]
for report in reports:
    print_report(report)

# ── Portfolio Summary (function calling functions) ────────────────────
all_totals = [r['metrics']['total'] for r in reports]
portfolio_revenue = sum(all_totals)
avg_customer_value = portfolio_revenue / len(reports)

print("=" * 60)
print(f"  Portfolio Revenue : ${portfolio_revenue:,.2f}")
print(f"  Avg Customer Value: ${avg_customer_value:,.2f}")
print("=" * 60)

Expected Output#

============================================================
  CUSTOMER ANALYTICS PIPELINE OUTPUT
============================================================

  Alice Johnson        | Northwest    | Platinum+
    Total: $4,156.75  |  Avg:  $346.40  |  Max:  $510.00  |  Purchases: 12
    Shipping Discount: 25%

  Bob Martinez         | Southwest    | Silver
    Total:   $421.05  |  Avg:  $140.35  |  Max:  $215.25  |  Purchases: 3
    Shipping Discount: 7%

  Carol Chen           | Northwest    | Gold
    Total: $1,650.75  |  Avg:  $330.15  |  Max:  $410.00  |  Purchases: 5
    Shipping Discount: 15%

  David Kim            | Southeast    | Standard
    Total:   $105.00  |  Avg:   $52.50  |  Max:   $60.00  |  Purchases: 2
    Shipping Discount: 0%

============================================================
  Portfolio Revenue : $6,333.55
  Avg Customer Value: $1,583.39
============================================================

Key Concepts Demonstrated#

ConceptWhere in Code
Type hints in signaturesdef classify_tier(total_spent: float, ...) -> str:
Docstrings"""Classify customer into loyalty tier..."""
Return dictionariescompute_metrics() returns structured result
dict.get() with defaultbase_discounts.get(tier, 0.00)
Function compositionbuild_customer_report() calls three other functions
List comprehension[build_customer_report(c) for c in customers]

Next: Jupyter Notebook →