Advanced Code Example — Loops and Iteration#

This example demonstrates for loops, while loops, accumulator patterns, nested loops, and loop control statements (break, continue) — all applied to a realistic multi-customer analytics workflow.


Business Scenario#

You are processing a monthly transaction dataset for a retail chain. You need to:

  1. Iterate through all customers and compute summary metrics
  2. Segment customers into tiers using a loop + branching pattern
  3. Use a while loop to simulate a data-quality retry process
  4. Use break and continue to control loop execution
  5. Build a regional revenue summary using nested loops

Code#

# ── Dataset ──────────────────────────────────────────────────────────
customers = [
    {'name': 'Alice Johnson',  'region': 'Northwest', 'purchases': [250.50, 180.75, 420.25, 310.00]},
    {'name': 'Bob Martinez',   'region': 'Southwest', 'purchases': [95.80, 215.25, 110.00]},
    {'name': 'Carol Chen',     'region': 'Northwest', 'purchases': [300.00, 290.75, 300.00]},
    {'name': 'David Kim',      'region': 'Southeast', 'purchases': [45.00, 60.00]},
    {'name': 'Eve Torres',     'region': 'Southwest', 'purchases': [520.00, 430.00, 500.00]},
    {'name': 'Frank Li',       'region': 'Northeast', 'purchases': []},   # empty — data issue
]

TIER_THRESHOLDS = {'Platinum': 1000, 'Gold': 500, 'Silver': 200}

def assign_tier(total):
    for tier_name, threshold in TIER_THRESHOLDS.items():
        if total >= threshold:
            return tier_name
    return 'Standard'

# ── FOR LOOP: Process all customers ──────────────────────────────────
print("=" * 58)
print("  CUSTOMER PROCESSING REPORT")
print("=" * 58)

regional_revenue = {}
tier_counts = {}
skipped = []

for customer in customers:
    name     = customer['name']
    region   = customer['region']
    purchases = customer['purchases']

    # CONTINUE: skip customers with no purchases
    if len(purchases) == 0:
        skipped.append(name)
        print(f"  ⚠  {name}: No purchase data — skipping")
        continue

    total = sum(purchases)
    avg   = total / len(purchases)
    tier  = assign_tier(total)

    # Accumulate regional revenue
    regional_revenue[region] = regional_revenue.get(region, 0.0) + total

    # Accumulate tier counts
    tier_counts[tier] = tier_counts.get(tier, 0) + 1

    print(f"  {name:<18} | {region:<12} | ${total:>8,.2f} | {tier}")

# ── WHILE LOOP: Retry simulation for skipped records ─────────────────
print(f"\n  Skipped: {skipped}")
print("\n  Simulating data retry for skipped records...")
retry_attempts = 0
max_retries = 3

while retry_attempts < max_retries:
    retry_attempts += 1
    print(f"    Attempt {retry_attempts}/{max_retries}: No new data found.")
    if retry_attempts == max_retries:
        print("    Max retries reached. Flagging for manual review.")
        break

# ── Regional Summary ──────────────────────────────────────────────────
print("\n" + "=" * 58)
print("  REGIONAL REVENUE")
print("=" * 58)
for region, revenue in sorted(regional_revenue.items()):
    print(f"  {region:<15} ${revenue:>10,.2f}")

# ── Tier Distribution ─────────────────────────────────────────────────
print("\n" + "=" * 58)
print("  TIER DISTRIBUTION")
print("=" * 58)
for tier, count in sorted(tier_counts.items()):
    bar = '█' * count
    print(f"  {tier:<10} {bar} ({count})")
print("=" * 58)

Expected Output#

==========================================================
  CUSTOMER PROCESSING REPORT
==========================================================
  ⚠  Frank Li: No purchase data — skipping
  Alice Johnson      | Northwest    | $1,161.50 | Platinum
  Bob Martinez       | Southwest    |   $421.05 | Silver
  Carol Chen         | Northwest    |   $890.75 | Gold
  David Kim          | Southeast    |   $105.00 | Standard
  Eve Torres         | Southwest    | $1,450.00 | Platinum

  Skipped: ['Frank Li']

  Simulating data retry for skipped records...
    Attempt 1/3: No new data found.
    Attempt 2/3: No new data found.
    Attempt 3/3: No new data found.
    Max retries reached. Flagging for manual review.

==========================================================
  REGIONAL REVENUE
==========================================================
  Northeast         $0.00
  Northwest     $2,052.25
  Southeast       $105.00
  Southwest     $1,871.05

==========================================================
  TIER DISTRIBUTION
==========================================================
  Gold       █ (1)
  Platinum   ██ (2)
  Silver     █ (1)
  Standard   █ (1)
==========================================================

Key Concepts Demonstrated#

Concept Where in Code
for loop over list of dicts Main customer processing loop
continue to skip records Empty purchases check
break to exit early Max retries in while loop
while loop with counter Data retry simulation
Accumulator dict (get default) regional_revenue.get(region, 0.0)
Nested for loop Tier thresholds iteration inside assign_tier()

Next: Jupyter Notebook →