1. Introduction to Iteration in Programming
In software engineering, repeating a set of instructions efficiently without duplicating code is fundamental. Imagine calculating monthly salaries for 10,000 employees, processing thousands of transaction records, or rendering frames in a video game—doing this manually line-by-line is impossible.
The process of repeatedly executing a block of code over a sequence of elements is known as Iteration or Looping. Python provides a clean, highly readable, and powerful for loop mechanism designed specifically for definite iteration—iterating over items of any sequence (like strings, lists, tuples, or ranges) in the exact order they appear.
2. Mechanics of the Python `for` Loop
1. Syntax and Execution Model
Unlike traditional languages like C, C++, or Java that use index-counter-based loops (e.g., for(int i=0; i<10; i++)), Python's for loop is fundamentally an iterator-based loop (similar to a for-each loop). It automatically fetches elements from a sequence one by one until the sequence is exhausted.
# Syntax Structure of a Python for loop:
for target_variable in iterable_sequence:
# Code block executed once per element
statement_1
statement_2
iterable_sequence, assigns it to target_variable, and executes the indented code block beneath. Once all items have been processed, the loop terminates naturally.
# Iterating over a String (character by character)
programming_language = "Python"
print("--- Iterating over String Characters ---")
for char in programming_language:
print(f"Current Character: {char}")
# Iterating over a List of strings
technologies = ["FastAPI", "Django", "PyTorch", "Pandas"]
print("\n--- Iterating over List Items ---")
for tech in technologies:
print(f"Technology Stack: {tech}")
--- Iterating over String Characters --- Current Character: P Current Character: y Current Character: t Current Character: h Current Character: o Current Character: n --- Iterating over List Items --- Technology Stack: FastAPI Technology Stack: Django Technology Stack: PyTorch Technology Stack: Pandas
3. Deep Dive: The `range()` Sequence Generator
When you need to execute a loop a specific number of times, or generate a arithmetic sequence of numbers on demand, Python provides the built-in range() function.
range() returns an immutable sequence object that generates numbers lazily (one at a time when requested) rather than storing all numbers in memory at once, making it extremely memory-efficient.
1. The Three Forms of `range()`
range(stop)- Starts at
0, steps by1, stops beforestop. range(5)→0, 1, 2, 3, 4range(start, stop)- Starts at
start, steps by1, stops beforestop. range(2, 7)→2, 3, 4, 5, 6range(start, stop, step)- Starts at
start, steps bystep, stops beforestop. range(1, 10, 2)→1, 3, 5, 7, 9
| Call Syntax Form | Parameter Arguments | Generated Sequence Example |
|---|---|---|
stop parameter in range(start, stop) is EXCLUSIVE. This means range(1, 5) includes 1, 2, 3, and 4, but **excludes 5**.
print("--- Form 1: range(5) ---")
for i in range(5):
print(i, end=" ")
print("\n\n--- Form 2: range(10, 15) ---")
for i in range(10, 15):
print(i, end=" ")
print("\n\n--- Form 3: range(0, 20, 5) ---")
for i in range(0, 20, 5):
print(i, end=" ")
print("\n\n--- Counting Downwards: range(10, 0, -2) ---")
for i in range(10, 0, -2):
print(i, end=" ")
print()
--- Form 1: range(5) --- 0 1 2 3 4 --- Form 2: range(10, 15) --- 10 11 12 13 14 --- Form 3: range(0, 20, 5) --- 0 5 10 15 --- Counting Downwards: range(10, 0, -2) --- 10 8 6 4 2
4. Accumulators, Running Totals, and Loop State
A common pattern in loop iteration is maintaining a running state across iterations—such as calculating sums, keeping counters, or filtering items. A variable declared outside the loop to store intermediate results is called an Accumulator.
# Calculate sum of all even numbers from 1 to 20
total_sum = 0
even_count = 0
for num in range(1, 21):
if num % 2 == 0:
total_sum += num # Accumulating sum
even_count += 1 # Counting occurrences
print(f"Total Even Numbers Found: {even_count}")
print(f"Sum of Even Numbers (1-20): {total_sum}")
Total Even Numbers Found: 10 Sum of Even Numbers (1-20): 110
5. Combining `for` Loops with `match-case` Structural Pattern Matching
In modern Python (3.10+), combining for loops with match-case pattern matching provides a remarkably clean architecture for processing lists of structured commands, records, or multi-format data payloads.
# A sequence of incoming transaction payloads (tuples/lists)
transactions = [
["DEPOSIT", 500.00],
["WITHDRAW", 200.00],
["TRANSFER", "ACC_9081", 150.00],
["WITHDRAW", 1000.00],
["UNKNOWN_OP"]
]
account_balance = 1000.00
print(f"Initial Account Balance: ${account_balance:.2f}\n")
# Iterating over each transaction payload and structural pattern matching
for tx in transactions:
match tx:
case ["DEPOSIT", amount]:
account_balance += amount
print(f"SUCCESS: Deposited ${amount:.2f}. New Balance: ${account_balance:.2f}")
case ["WITHDRAW", amount] if amount <= account_balance:
account_balance -= amount
print(f"SUCCESS: Withdrew ${amount:.2f}. New Balance: ${account_balance:.2f}")
case ["WITHDRAW", amount] if amount > account_balance:
print(f"FAILED : Overdraft prevented for withdrawal of ${amount:.2f}!")
case ["TRANSFER", target_acc, amount] if amount <= account_balance:
account_balance -= amount
print(f"SUCCESS: Transferred ${amount:.2f} to {target_acc}. New Balance: ${account_balance:.2f}")
case _:
print(f"ERROR : Unrecognized transaction payload -> {tx}")
print(f"\nFinal Account Balance: ${account_balance:.2f}")
Initial Account Balance: $1000.00 SUCCESS: Deposited $500.00. New Balance: $1500.00 SUCCESS: Withdrew $200.00. New Balance: $1300.00 SUCCESS: Transferred $150.00 to ACC_9081. New Balance: $1150.00 FAILED : Overdraft prevented for withdrawal of $1000.00! ERROR : Unrecognized transaction payload -> ['UNKNOWN_OP'] Final Account Balance: $1150.00
6. Nested `for` Loops and Index Tracking
A loop can be placed inside another loop. This is known as a Nested Loop. The inner loop executes completely every single time the outer loop runs once.
# Generating a multiplication table grid (1 to 3)
print("--- Multiplication Table Grid (1x1 to 3x3) ---")
for row in range(1, 4):
for col in range(1, 4):
product = row * col
print(f"{row}x{col}={product:<2}", end=" | ")
print() # Newline after outer row completes
--- Multiplication Table Grid (1x1 to 3x3) --- 1x1=1 | 1x2=2 | 1x3=3 | 2x1=2 | 2x2=4 | 2x3=6 | 3x1=3 | 3x2=6 | 3x3=9 |
Index Tracking with `enumerate()`
When iterating over a sequence, you often need both the item value AND its zero-based positional index. Instead of maintaining a manual counter, use Python's built-in enumerate() function:
fruits = ["Apple", "Banana", "Cherry", "Dragonfruit"]
# enumerate() returns (index, item) tuples automatically
for idx, fruit in enumerate(fruits, start=1):
print(f"Rank #{idx}: {fruit}")
Rank #1: Apple Rank #2: Banana Rank #3: Cherry Rank #4: Dragonfruit
7. The `for-else` Clause (Unique Python Feature)
Python offers a unique construct: an else block attached directly to a for loop. The else block executes **ONLY IF the loop completes all iterations naturally** without being interrupted by a break statement.
target_number = 13
# Checking if number is prime using for-else
for i in range(2, target_number):
if target_number % i == 0:
print(f"{target_number} is NOT a prime number (divisible by {i}).")
break
else:
# Executes ONLY if loop finishes without hitting 'break'
print(f"{target_number} IS a prime number!")
13 IS a prime number!
8. Frequently Asked Interview Questions with Answers
for loops are index-counter based (for(int i=0; i). In Python, for loops are iterator-based (like for-each loops). They iterate directly over items of any sequence or iterable object without requiring manual index tracking.
range() returns a range object that generates numbers lazily on demand (calculating values as needed during iteration). It uses constant $O(1)$ memory space regardless of whether it represents 10 numbers or 10,000,000 numbers, whereas a list pre-allocates memory for all elements upfront.
else clause attached to a for loop executes **only when the loop finishes iterating over all items normally**. If the loop terminates prematurely due to a break statement, the else block is completely skipped.
for i in range(len(seq)): item = seq[i] works, it is considered unpythonic. Using for i, item in enumerate(seq): is cleaner, yields both index and value directly via tuple unpacking, improves readability, and adheres to PEP 8 standards.
step = 0 raises an immediate ValueError: range() arg 3 must not be zero because a zero step size would cause an infinite loop condition.
9. Homework & Practical Assignments
Task 1: Lesson 13 Specific Exercise — Pattern Match Command Batcher
Create a script named batch_processor.py inside your lesson_13 folder:
- Define a list of mixed event payloads:
events = [ ["LOGIN", "user_101"], ["PURCHASE", "user_101", 250.50], ["LOGOUT", "user_101"], ["UNKNOWN"] ] - Iterate over
eventsusing aforloop. - Inside the loop, use
match-casepattern matching to process each event payload and display formatted output using f-strings.
Task 2: Comprehensive Review Assignment (Lessons 1 to 13 Master Project)
Project Goal: Build a complete terminal-based Automated Payroll and Attendance System payroll_master_system.py integrating all foundational concepts from Lesson 1 through Lesson 13.
Project Requirements Checklist:
- Setup & Documentation (Lessons 1-4): Write complete docstrings explaining script goals. Set up clean console banners using
print()parameters and follow PEP 8 standards. - Variables & Data Types (Lessons 5-6): Define company name constants, tax rates (floats), and base pay metrics.
- Operators & Calculations (Lesson 7): Calculate gross pay, tax deductions, net salary, and hourly averages using arithmetic operators (
*,/,-) and rounding. - String Processing (Lesson 8): Prompt for employee full name and raw email string. Use
.strip(),.title(), and.split("@")to clean data and parse corporate email domains. - Formatted Output & f-Strings (Lesson 9): Print an itemized payroll paystub using f-strings with currency format specifiers (
:,.2f) and text alignment padding (:<15,:>10). - Boolean Logic & Comparisons (Lesson 10): Evaluate overtime eligibility using logical operators (e.g.,
hours_worked > 40 and employee_status == "active"). - Conditional Control Flow (Lesson 11): Assign performance bonus tiers (Tier 1: 15%, Tier 2: 10%, Tier 3: 5%) using an
if-elif-elseladder. - Pattern Matching (Lesson 12): Process department designation codes using
match-case:case ["ENG", level]→ Assign Engineering allowance multiplier.case ["HR", level]→ Assign Human Resources allowance multiplier.case _→ Assign default general allowance.
- Iteration & Range (Lesson 13): Store a batch list of employee attendance records (hours worked per day over a 5-day week). Use a
forloop withrange()orenumerate()to iterate through daily hours, calculate running totals using accumulators, and output daily logs.
10. File & Workspace Directory Structure
Standard Course Workspace Layout:
Ensure all exercise files are stored inside their corresponding lesson directories:
python_mastery_course/
│
├── lesson_01/
├── lesson_02/
├── lesson_03/
├── lesson_04/
├── lesson_05/
├── lesson_06/
├── lesson_07/
├── lesson_08/
├── lesson_09/
├── lesson_10/
├── lesson_11/
├── lesson_12/
│
└── lesson_13/
├── basic_for_loop.py
├── range_variations_demo.py
├── accumulator_pattern.py
├── loop_with_match_case.py
├── nested_loops_demo.py
├── enumerate_demo.py
├── for_else_demo.py
├── batch_processor.py
└── payroll_master_system.py <-- (Lesson 1-13 Master Review Project)
OnlineCBT