🔁 What is a Loop?

A loop repeats a block of code — once for each item in a list, or while a condition stays true. It's how Python processes 10 transactions or 10 million with the same 3 lines.

for item in collection:

In plain English: "for every transaction in the list, do this."

Python has 2 loop types: for (iterate over a known collection) and while (keep going while a condition holds). You will use for 90% of the time.

🎯 The 2 Loop Types

for
for x in list:
Runs once per item. Best for known collections.
while
while flag:
Runs as long as condition is True. Unknown count.
range
range(0, 10)
Generate a sequence of integers to loop over.
enumerate
for i, x in …
Get index + value together. Cleaner than manual counters.
zip
zip(a, b)
Loop over two lists in parallel. Pairs matched by index.

🏦 The Business Scenario

💳
Banking · SouthBank India
Processing a Batch of Daily Transactions

A Mumbai fraud-detection team receives a list of the day's transactions. They need to total the amounts, flag any over ₹50,000 for review, and skip any that are already cancelled. A for loop runs through all of them in microseconds — the exact same pattern scales to 10M transactions with Pandas later.

6
Transactions today
2
Flagged for review
<1ms
Total processing time

💻 Step 1: A Basic for Loop

process_transactions.py ▶ Pre-computed output below
# Output Total processed: ₹177,500 Number of transactions: 6

🔍 Step 2: enumerate with Fraud Flags

You need the index too, so you can cite which transaction failed. Use enumerate() — cleaner than tracking a counter manually.

flag_large.py ▶ Real pattern from fraud teams
# Output ✔ Txn #1: ₹1,500 — OK ✔ Txn #2: ₹45,000 — OK ⚠️ Txn #3: ₹72,000 — review! ✔ Txn #4: ₹800 — OK ⚠️ Txn #5: ₹55,000 — review! ✔ Txn #6: ₹3,200 — OK

🛑 Step 3: break and continue

Skip certain items with continue. Stop the loop early with break. Both are used in every production script.

first_fraud.py ▶ Stop at first suspicious txn
# Output processed ₹1,500 processed ₹45,000 🚨 First large txn: ₹72,000

🔄 Step 4: while Loop — Retrying an API Call

Use while when you don't know how many iterations you need — e.g. retrying a flaky API call until it succeeds or you hit a limit.

retry_api.py ▶ Simulated retry loop
# Example run (random outcome) Attempt 1 — calling payment API… Attempt 2 — calling payment API… Attempt 3 — calling payment API… ✅ Payment confirmed.

🌍 Also Used In

The Same Pattern Across Every Domain

📱
for user in subscribers: send_sms(user)
Telecom — send billing alerts to every subscriber
🏥
for claim in daily_claims: validate(claim)
Insurance — iterate through each claim for validation
🚚
for pkg in warehouse: route(pkg, zone)
Logistics — assign every package to a delivery zone
🤖
for epoch in range(100): train(model, X, y)
AI & ML — every neural network is trained with a for loop over epochs

🤖 AI & Machine Learning Connection

Every single machine learning model is trained with a for epoch in range(n_epochs) loop. PyTorch and TensorFlow dress it up as model.fit() — but under the hood it's the exact same for you just learned, running millions of times over a dataset. Master this lesson and you've mastered the backbone of AI training.

pandas scikit-learn PyTorch TensorFlow

🎯 Mini Challenge

Calculate Average Insurance Claim

Given claims = [12000, 45000, 8500, 0, 67000, 0, 15000], write a loop that: (1) skips cancelled claims (amount = 0) using continue, (2) totals the valid ones, (3) prints the average. Expected: average of 5 valid claims ≈ ₹29,500.

Start with total = 0 and count = 0. Loop with for amount in claims:. Inside: if amount == 0: continue, then total += amount and count += 1. After the loop: average = total / count. Print with an f-string.

🎤 Interview Questions

Use for when you know what you're iterating over (a list, a range, a file) — you don't need to track a counter, Python does it. Use while when you don't know how many iterations you need — e.g. "retry this API call until it succeeds or 5 attempts are used". In practice, for covers ~90% of loops in real code.
break exits the loop entirely — skip all remaining iterations. continue skips the current iteration and jumps to the next one. Example: reviewing transactions, continue on cancelled ones (skip this one) vs break on the first fraud (stop checking). Both affect only the innermost loop.
enumerate(lst) returns (index, item) pairs — more readable, less error-prone. Compare: for i in range(len(lst)): x = lst[i] (noisy) vs for i, x in enumerate(lst): (clean). It's also faster and works on any iterable, not just sequences. PEP 8 and every Python linter push you to use enumerate.
zip(a, b) pairs items by index — parallel iteration. If customers = [...] and balances = [...], for c, b in zip(customers, balances): gives one (customer, balance) per step. Nested loops run every combination — for c in customers: for b in balances: runs len(customers) × len(balances) times. Use zip when lists are aligned; nested loops when you need a cartesian product (e.g. comparing every pair).
An infinite loop is a while loop whose condition never becomes False. Classic bug: while x > 0: with no code that decreases x. Avoid by (1) always changing the condition variable inside the loop, (2) adding a max-iteration guard (if attempt > 100: break), (3) using for with a bounded range() when possible. for loops in Python can't be infinite on a finite collection — this is why interviewers prefer for in most situations.

🧠 Quick Quiz

Question 1 of 5
How many times does this loop print?
for i in range(5): print(i)
Question 2 of 5
Which keyword skips the current iteration and moves to the next?
Question 3 of 5
What does enumerate(["a","b","c"]) give you?
Question 4 of 5
Which loop should you use to retry an API call up to 5 times?
Question 5 of 5
What will for c, b in zip(["Priya","Ravi"], [1000, 2000]): print(c, b) print?
0
/5

📋 Quick Cheatsheet

PatternSyntaxUse When
Basic forfor x in lst:Iterate over a list, tuple, or string
Counted loopfor i in range(n):Repeat n times or use numeric index
Index + valuefor i, x in enumerate(lst):Need both position and value
Parallel loopfor a, b in zip(l1, l2):Two lists paired by index
While loopwhile cond:Retry / unknown iterations
Skip itemcontinueSkip to next iteration
Stop loopbreakExit loop entirely
Dict loopfor k, v in d.items():Iterate dictionary pairs

⚠️ Common Mistakes

Forgetting to update the while condition
Classic infinite loop: while x > 0: but nothing inside ever changes x. Always update the condition variable inside the loop, or add a break.
Modifying a list while iterating over it
for x in lst: lst.remove(x) skips items and silently corrupts results. Iterate over a copy: for x in lst[:]:, or use a list comprehension: lst = [x for x in lst if keep(x)].
Using range(len(lst)) when enumerate is cleaner
Write for i, x in enumerate(lst): instead of for i in range(len(lst)): x = lst[i]. Every Python reviewer will push back on the longer form.
Mis-indenting the loop body
Python's structure is the indentation. If break is at the wrong indent level, it exits the wrong loop. Use 4 spaces consistently — avoid mixing tabs and spaces.

✦ Key Takeaways

  • Use for for known collections (lists, files, ranges) — ~90% of real loops
  • Use while for retry patterns or when iteration count is unknown
  • range(n) generates 0..n-1 — the end is exclusive
  • enumerate() gives you (index, item) — always prefer it over range(len(…))
  • zip() loops two lists in parallel, pairing items by index
  • break exits the loop; continue skips one iteration
  • Every ML training run is a for loop under the hood
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

You've mastered loops.
Now go loop over real datasets.

Join the Best AI Program: The AI-Era Analyst — 5 months, fully online, with placement assistance. Week 1 is free.

Explore The AI-Era Analyst →