Advanced Code Example — Branching and Control Flow#
This example builds a multi-rule business decision system that combines customer classification, fraud detection signals, and pricing logic — all implemented with branching and control flow.
Business Scenario#
You are building an automated customer evaluation tool for a retail analytics team. For each customer record, the system must:
- Classify the customer into a loyalty tier (Platinum / Gold / Silver / Standard)
- Evaluate shipping discount eligibility based on region and tier
- Check for potential fraud signals based on transaction patterns
- Generate a customer status summary
Code#
# ── Customer Record ─────────────────────────────────────────────────
customer = {
'name': 'Alice Johnson',
'region': 'Northwest',
'total_spent': 1257.30,
'purchase_count': 12,
'avg_transaction': 104.78,
'days_since_last_purchase': 8,
'flagged_transactions': 0,
'account_age_days': 540
}
name = customer['name']
region = customer['region']
total_spent = customer['total_spent']
purchase_count = customer['purchase_count']
avg_txn = customer['avg_transaction']
days_inactive = customer['days_since_last_purchase']
flags = customer['flagged_transactions']
account_age = customer['account_age_days']
# ── 1. Loyalty Tier Classification ──────────────────────────────────
if total_spent >= 1500 and purchase_count >= 15:
tier = 'Platinum+'
elif total_spent >= 1000 and purchase_count >= 10:
tier = 'Platinum'
elif total_spent >= 500 or purchase_count >= 5:
tier = 'Gold'
elif total_spent >= 200:
tier = 'Silver'
else:
tier = 'Standard'
# ── 2. Shipping Discount Logic ───────────────────────────────────────
if tier in ('Platinum+', 'Platinum') and region == 'Northwest':
shipping_discount = 0.20
shipping_label = '20% (Top Tier + Home Region)'
elif tier in ('Platinum+', 'Platinum'):
shipping_discount = 0.15
shipping_label = '15% (Top Tier)'
elif tier == 'Gold' and region in ('Northwest', 'Southwest'):
shipping_discount = 0.10
shipping_label = '10% (Gold + Regional)'
elif tier == 'Gold':
shipping_discount = 0.07
shipping_label = '7% (Gold Standard)'
else:
shipping_discount = 0.00
shipping_label = 'None'
# ── 3. Fraud Signal Evaluation ───────────────────────────────────────
fraud_signals = []
if flags > 0:
fraud_signals.append(f'{flags} flagged transaction(s) on record')
if avg_txn > 500:
fraud_signals.append('Unusually high average transaction amount')
if account_age < 30 and total_spent > 1000:
fraud_signals.append('High spend on new account')
if purchase_count > 20 and days_inactive < 1:
fraud_signals.append('Unusual purchase frequency')
fraud_risk = 'HIGH' if len(fraud_signals) >= 2 else ('MEDIUM' if fraud_signals else 'LOW')
# ── 4. Engagement Status ─────────────────────────────────────────────
if days_inactive <= 7:
engagement = 'Active'
elif days_inactive <= 30:
engagement = 'Recent'
elif days_inactive <= 90:
engagement = 'At Risk'
else:
engagement = 'Churned'
# ── Report Output ────────────────────────────────────────────────────
print("=" * 52)
print(f" CUSTOMER EVALUATION: {name}")
print("=" * 52)
print(f" Loyalty Tier : {tier}")
print(f" Engagement : {engagement}")
print(f" Shipping Disc. : {shipping_label}")
print(f" Fraud Risk : {fraud_risk}")
if fraud_signals:
print("\n Fraud Signals Detected:")
for signal in fraud_signals:
print(f" ⚠ {signal}")
else:
print("\n No fraud signals detected.")
print("=" * 52)Expected Output#
====================================================
CUSTOMER EVALUATION: Alice Johnson
====================================================
Loyalty Tier : Platinum
Engagement : Recent
Shipping Disc. : 20% (Top Tier + Home Region)
Fraud Risk : LOW
No fraud signals detected.
====================================================Key Concepts Demonstrated#
| Concept | Where in Code |
|---|---|
Multi-level elif chain |
Loyalty tier classification (5 levels) |
in operator for membership |
tier in ('Platinum+', 'Platinum') |
Compound and / or |
Shipping discount rules |
| List accumulation with branching | fraud_signals.append(...) |
| Nested condition evaluation | Account age × spend fraud check |
len() on result list to determine risk |
len(fraud_signals) >= 2 |
Next: Jupyter Notebook →