🔁 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.
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
🏦 The Business Scenario
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.
💻 Step 1: A Basic for Loop
🔍 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.
🛑 Step 3: break and continue
Skip certain items with continue. Stop the loop early with break. Both are used in every production script.
🔄 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.
🌍 Also Used In
The Same Pattern Across Every Domain
🤖 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.
🎯 Mini Challenge
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.
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
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).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
for i in range(5): print(i)enumerate(["a","b","c"]) give you?for c, b in zip(["Priya","Ravi"], [1000, 2000]): print(c, b) print?📋 Quick Cheatsheet
| Pattern | Syntax | Use When |
|---|---|---|
| Basic for | for x in lst: | Iterate over a list, tuple, or string |
| Counted loop | for i in range(n): | Repeat n times or use numeric index |
| Index + value | for i, x in enumerate(lst): | Need both position and value |
| Parallel loop | for a, b in zip(l1, l2): | Two lists paired by index |
| While loop | while cond: | Retry / unknown iterations |
| Skip item | continue | Skip to next iteration |
| Stop loop | break | Exit loop entirely |
| Dict loop | for k, v in d.items(): | Iterate dictionary pairs |
⚠️ Common Mistakes
while conditionwhile x > 0: but nothing inside ever changes x. Always update the condition variable inside the loop, or add a break.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)].range(len(lst)) when enumerate is cleanerfor 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.break is at the wrong indent level, it exits the wrong loop. Use 4 spaces consistently — avoid mixing tabs and spaces.✦ Key Takeaways
- Use
forfor known collections (lists, files, ranges) — ~90% of real loops - Use
whilefor retry patterns or when iteration count is unknown range(n)generates0..n-1— the end is exclusiveenumerate()gives you(index, item)— always prefer it overrange(len(…))zip()loops two lists in parallel, pairing items by indexbreakexits the loop;continueskips one iteration- Every ML training run is a
forloop under the hood
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 →