For Loops
Automate repetitive tasks by iterating over sequences.
🔄 Introduction: The "Assembly Line" Analogy
Imagine you are working in a car factory. You are standing at an assembly line, and a conveyor belt is bringing car doors to you, one by one. Your job is to attach a handle to every single door that passes by.
In programming, the conveyor belt is the "Sequence" (List/String), the car door is the "Item", and you are the "For Loop".
A for loop is designed to handle Definite Iteration. This means you know (or the computer knows) exactly how many items are waiting on the conveyor belt before you even start. Unlike a `while` loop which runs "until something happens", a `for` loop runs "for every item in the collection".
🎯 Topic 1: Anatomy of a for Loop
The syntax of a Python for loop is remarkably like plain English: "For every item in this sequence, do action."
[Image of flowchart showing function call execution flow]📝 Syntax Breakdown:
# Code to execute for EACH item
1. temp_var: A temporary variable that holds the current item being processed. You can name this anything (e.g., i, item, x).
2. collection: The list, string, or range you want to loop through.
3. The Colon (:): Don't forget this! It tells Python the loop body is starting.
💻 Example: The Fruit Basket
🔢 Topic 2: The Power of range()
What if you don't have a list? What if you just want to do something 100 times? Or count from 1 to 10? You don't need to manually type [1, 2, 3, 4...].
The range() function creates a mathematical sequence of numbers on the fly. It is efficient and fast.
📊 Understanding Range Arguments:
Starts at 0, goes up to (but NOT including) 'stop'.
range(3) -> 0, 1, 2
Starts at 'start', goes up to (but NOT including) 'stop'.
range(2, 5) -> 2, 3, 4
Starts at 'start', adds 'step' each time.
range(0, 10, 2) -> 0, 2, 4, 6, 8
💻 Example: The Countdown
📦 Topic 3: Nested Loops (Loop inside Loop)
You can put a loop inside another loop. This is common when working with matrices, grids, or complex data combinations.
Analogy: The Clock.
The "Seconds Hand" loop runs 60 times (0 to 59). Only after it finishes does the "Minutes Hand" loop move once. Then the seconds loop starts all over again from 0.
💻 Example: Coordinate Grid
🚀 Topic 4: Advanced Iteration Techniques
In interviews and real projects (Data Science!), you rarely just loop through a simple list. You need more power.
1. using enumerate()
Usually, a for loop gives you the item (apple), but not the position (0). enumerate() gives you BOTH.
for index, val in enumerate(colors):
print(f"Rank {index+1}: {val}")
2. Looping Dictionaries
Dictionaries have keys and values. You can loop through them using .items().
for name, score in scores.items():
print(f"{name} got {score} marks")
📚 Module Summary
- For Loop: Best for definite iteration (Lists, Strings, Range).
- Range(start, stop, step): Generates number sequences efficiently.
- Nested Loops: Loop inside a loop (Think Clock or Matrix).
- Enumerate: Gets you the index AND the value together.
- Dictionary Items: Use
.items()to get key-value pairs.
🤔 Interview Q&A
Tap on the questions below to reveal the answers.
Use a For Loop when you know exactly how many times you need to iterate (e.g., iterating through a list of 10 items).
Use a While Loop when you don't know the end point and want to loop until a condition changes (e.g., waiting for user input).
No. In Python, the upper bound is always exclusive. range(5) generates numbers 0, 1, 2, 3, 4. It stops BEFORE it hits 5.
It is dangerous! Adding or removing items from a list while you are looping through it can cause items to be skipped or the loop to crash. It's better to create a new list or iterate over a copy of the list (list[:]).
Don't create a separate counter variable! The Pythonic way is to use enumerate().
Example: for index, item in enumerate(my_list):