Python Loops & Iteration
Master sequence iteration and repeated execution: for loops, while loops, the range() function, loop-control variables, break, continue, loops combined with conditions, and practical dataset aggregation for data analytics.
1. Why Loops?
In programming and data analytics, you constantly need to repeat tasks: inspect 10,000 sales records, send 500 emails, or calculate totals across 12 monthly columns.
print("Amit")
print("Priya")
print("Rahul")
# What if you have 10,000 names?
# You cannot write 10,000 print lines!names = ["Amit", "Priya", "Rahul"]
for name in names:
print(name)
# Works for 3 names or 3,000,000 names!2. π₯ The FOR Loop
Python's for statement iterates over the items of any sequence (such as a list, string, or range) in the exact order they appear:
for name in names:
Β Β Β Β print(name)
name = "Amit" β printname = "Priya" β printname = "Rahul" β printfor loop that iterates through names and prints each name.3. π₯ The range() Function
When you need to iterate over a sequence of numbers, the built-in range() function is standard. It generates numbers on demand without storing the whole list in memory:
| Syntax Form | Explanation | Generated Numbers |
|---|---|---|
range(stop) | Starts at 0, increments by 1, stops before stop | range(5) β 0, 1, 2, 3, 4 |
range(start, stop) | Starts at start, increments by 1, stops before stop | range(1, 6) β 1, 2, 3, 4, 5 |
range(start, stop, step) | Starts at start, increments by step, stops before stop | range(2, 11, 2) β 2, 4, 6, 8, 10 |
range(1, 10) stops at 9, NOT 10. If you need numbers 1 through 10 inclusive, your stop parameter must be 11: range(1, 11).π§ Predict Then Run: range() Expressions
for loop with range() that prints even numbers from 2 to 10 (inclusive).4. π₯ The WHILE Loop
A while loop continues executing its code block as long as its condition remains True:
count += 1), the condition will never become False, and Python will run forever, freezing your program!while loop that counts from 1 to 5.5. π₯ FOR vs WHILE: Which One Should You Use?
Use when you know the collection or number of times in advance:
- Iterating over lists, tuples, dictionaries
- Running exactly N times with
range() - Scanning rows in a dataset
Use when repetition depends on a dynamic condition:
- Waiting for user to enter valid input
- Polling an API endpoint until data is ready
- Simulations that run until convergence
Scenario Chooser: Pick FOR or WHILE
6. π₯ BREAK & CONTINUE
Fine-tune the control flow inside any loop using break and continue:
Terminates the entire loop immediately. Execution jumps to the next statement outside the loop.
Skips the rest of the current iteration and immediately advances to the next item in the loop.
cities. If city == "Mumbai", print "Found Mumbai!" and break. Otherwise print the city.scores. If score < 0, use continue to skip it. Otherwise print score.7. π₯ Combining Loops + Conditions
In data analytics, combining loops and conditions is the foundational pattern for data filtering:
Visits every value in the dataset sequentially.
Decides what to do with each individual value.
sales = [45000, 70000, 30000, 90000] and print only sales >= 50000.8. π₯ Practical Data Analytics: The Accumulator Pattern
In data analytics, you don't just print valuesβyou calculate aggregates like totals and counts. This is done with the accumulator pattern:
- Initialize
total_sales = 0andhigh_sales_count = 0 - Iterate through
sales = [45000, 32000, 78000, 25000, 60000] - Accumulate all sales into
total_sales - If
sale >= 50000, incrementhigh_sales_countby 1 - Print the totals after the loop!
9. Common Beginner Mistakes Checklist
| Mistake | Incorrect Code | Correct Code | Why It Fails |
|---|---|---|---|
Forgetting the colon : | for item in items | for item in items: | Colons are mandatory in Python to introduce loop blocks. |
| Missing while update (Infinite loop) | while i < 5: print(i) | while i < 5: print(i); i += 1 | If i never updates, condition stays True forever. |
Expecting range(1, 5) to include 5 | range(1, 5) | range(1, 6) | The stop argument in range() is strictly non-inclusive. |
Confusing break with continue | Using break to skip an item | Using continue to skip an item | break kills the entire loop; continue only skips the current iteration. |
| Accidental indentation of summary print | Indented print(total) | Unindented print(total) | Indented code runs on every single iteration instead of once after the loop. |
10. π₯ Final Live Challenge: Customer Transaction Analyzer
Synthesize everything you've learned: loop traversal, loop control with continue, filtering with if, and accumulation!
- Dataset:
transactions = [120, 850, -45, 450, 920, -15, 600] - Rule 1 (Refunds): If a transaction is negative (
< 0), skip it usingcontinue! - Rule 2 (Revenue): Add valid transaction amounts to
total_revenue. - Rule 3 (Premium Orders): If a transaction is
>= 500, incrementpremium_ordersby 1. - Print
"Net Revenue:", total_revenueand"Premium Orders:", premium_ordersafter the loop finishes.
11. Core Concept Quick Reference
12. Comprehensive Knowledge Assessment
Test your mastery of Python loops, range generation, while termination, and flow control:
Python Loops Mastery Quiz
Test your conceptual understanding of Python iteration, range(), while loop conditions, break, and continue.
1. What sequence of numbers is generated by Python's range(2, 8, 2)?