Python 3.12+ Iteration & Control Flow Data Processing Core

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.

Read Time: 20 mins
Primary Source: Official Python 3.12+ Documentation
Interactive Labs: 7 Live Coding Workbenches
1

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.

❌ Manually Repeating Code (Brittle & Tedious)
print("Amit")
print("Priya")
print("Rahul")
# What if you have 10,000 names?
# You cannot write 10,000 print lines!
βœ… Using a Python Loop (DRY & Scalable)
names = ["Amit", "Priya", "Rahul"]

for name in names:
    print(name)
# Works for 3 names or 3,000,000 names!
The DRY Principle:
DRY stands for Don't Repeat Yourself. Loops eliminate repetitive boilerplate, prevent copy-paste bugs, and let you automate operations over massive datasets with just 2 lines of code.
2

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:

names = ["Amit", "Priya", "Rahul"]

for name in names:
Β Β Β Β print(name)
How the Loop Variable Changes on Each Iteration
Iteration 1: name = "Amit" β†’ print
Iteration 2: name = "Priya" β†’ print
Iteration 3: name = "Rahul" β†’ print
βœ“ Sequence exhausted β†’ Loop terminates cleanly
Exercise 1: Write Your First FOR Loop
Hands-on Lab
Task: Type a for loop that iterates through names and prints each name.
3

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 FormExplanationGenerated Numbers
range(stop)Starts at 0, increments by 1, stops before stoprange(5) β†’ 0, 1, 2, 3, 4
range(start, stop)Starts at start, increments by 1, stops before stoprange(1, 6) β†’ 1, 2, 3, 4, 5
range(start, stop, step)Starts at start, increments by step, stops before stoprange(2, 11, 2) β†’ 2, 4, 6, 8, 10
Critical Rule: The "Stop" Value is Excluded!
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

range(5)
range(2, 6)
range(1, 10, 2)
Exercise 2: Generate Even Numbers 2 to 10
Coding Task
Task: Write a for loop with range() that prints even numbers from 2 to 10 (inclusive).
4

4. πŸ”₯ The WHILE Loop

A while loop continues executing its code block as long as its condition remains True:

The While Loop Lifecycle
1. Check Condition (e.g., count <= 5)
↓ True
2. Execute Block (e.g., print(count))
↓
3. UPDATE Loop Variable! (count += 1)
β†Ί Loop back to Step 1
The Danger of Infinite Loops:
If you forget to increment or update your control variable (e.g. count += 1), the condition will never become False, and Python will run forever, freezing your program!
Exercise 3: Write a Complete WHILE Loop
Coding Task
Task: Write a while loop that counts from 1 to 5.
5

5. πŸ”₯ FOR vs WHILE: Which One Should You Use?

FOR Loop (Definite Iteration)

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
WHILE Loop (Indefinite Iteration)

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

1. Processing a list of 500 customer names from an Excel export.
2. Prompting a user to enter their password until they type it correctly.
3. Calculating monthly interest until an investment balance doubles.
4. Summing sales figures for each of the 12 months in a list.
6

6. πŸ”₯ BREAK & CONTINUE

Fine-tune the control flow inside any loop using break and continue:

πŸ›‘ break (Emergency Exit)

Terminates the entire loop immediately. Execution jumps to the next statement outside the loop.

⏭️ continue (Skip Ahead)

Skips the rest of the current iteration and immediately advances to the next item in the loop.

Exercise 6A: Use `break` to Stop When Target is Found
Break Lab
Task: Loop through cities. If city == "Mumbai", print "Found Mumbai!" and break. Otherwise print the city.
Exercise 6B: Use `continue` to Skip Invalid Data
Continue Lab
Task: Loop through scores. If score < 0, use continue to skip it. Otherwise print score.
7

7. πŸ”₯ Combining Loops + Conditions

In data analytics, combining loops and conditions is the foundational pattern for data filtering:

THE LOOP:

Visits every value in the dataset sequentially.

THE CONDITION:

Decides what to do with each individual value.

Exercise: Filter High-Value Sales
Data Filter
Task: Loop through sales = [45000, 70000, 30000, 90000] and print only sales >= 50000.
8

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:

Dataset
5 Sales Records
Threshold Target
>= 50,000
Outputs
Total & Count
Exercise: Calculate Total Revenue & High Sales Count
Analytics Workbench
Requirements:
  • Initialize total_sales = 0 and high_sales_count = 0
  • Iterate through sales = [45000, 32000, 78000, 25000, 60000]
  • Accumulate all sales into total_sales
  • If sale >= 50000, increment high_sales_count by 1
  • Print the totals after the loop!
9

9. Common Beginner Mistakes Checklist

MistakeIncorrect CodeCorrect CodeWhy It Fails
Forgetting the colon :for item in itemsfor 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 += 1If i never updates, condition stays True forever.
Expecting range(1, 5) to include 5range(1, 5)range(1, 6)The stop argument in range() is strictly non-inclusive.
Confusing break with continueUsing break to skip an itemUsing continue to skip an itembreak kills the entire loop; continue only skips the current iteration.
Accidental indentation of summary printIndented print(total)Unindented print(total)Indented code runs on every single iteration instead of once after the loop.
10

10. πŸ”₯ Final Live Challenge: Customer Transaction Analyzer

Synthesize everything you've learned: loop traversal, loop control with continue, filtering with if, and accumulation!

πŸ“‹ Analytical Business Rules:
  • Dataset: transactions = [120, 850, -45, 450, 920, -15, 600]
  • Rule 1 (Refunds): If a transaction is negative (< 0), skip it using continue!
  • Rule 2 (Revenue): Add valid transaction amounts to total_revenue.
  • Rule 3 (Premium Orders): If a transaction is >= 500, increment premium_orders by 1.
  • Print "Net Revenue:", total_revenue and "Premium Orders:", premium_orders after the loop finishes.
Final Capstone: Transaction Log Aggregator
Capstone Challenge
11

11. Core Concept Quick Reference

What does a for loop do?
Iterates through each element in an iterable sequence in order.
What does range(start, stop, step) do?
Generates numbers from start up to (but excluding) stop by step.
What is a while loop?
Repeatedly executes code as long as its condition remains True.
What does break do?
Immediately exits the innermost enclosing loop.
What does continue do?
Skips the rest of the current iteration and jumps to the next.
Why use an accumulator?
To compute running totals, counts, or averages across datasets.
12

12. Comprehensive Knowledge Assessment

Test your mastery of Python loops, range generation, while termination, and flow control:

TEST YOUR KNOWLEDGE

Python Loops Mastery Quiz

Test your conceptual understanding of Python iteration, range(), while loop conditions, break, and continue.

Question 1 of 5Current Score: 0 / 0
Q1

1. What sequence of numbers is generated by Python's range(2, 8, 2)?