Part 03 / Topic 11 of 12
Common loop patterns
| Pattern | Idea | Start value |
|---|---|---|
| Counter | count how many items match | count = 0, then count += 1 |
| Accumulator | build a total | total = 0, then total += x |
| Search | find the first match, then break |
found = None or use loop else |
Real-world example: a day's UPI payments.
payments = [250, 1200, 80, 5000, 450]
# Counter: how many payments above ₹1,000?
big = 0
for amount in payments:
if amount > 1000:
big += 1
print(f"Big payments: {big}") # Big payments: 2
# Accumulator: total spent
total = 0
for amount in payments:
total += amount
print(f"Total: ₹{total:,}") # Total: ₹6,980
# Search: first payment under ₹100
first_small = None
for amount in payments:
if amount < 100:
first_small = amount
break
print(f"First small payment: ₹{first_small}") # First small payment: ₹80
Done here? The practice set for Part 3 — 7 exercises with solutions — is on the part page.