DSPython Logo DSPython

For Loops

Automate repetitive tasks by iterating over sequences.

Python Basics Beginner 30 min

🔄 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:

for temp_var in collection:
    # 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

# We have a list of fruits
basket = ["Apple", "Banana", "Mango"]

# Loop through them one by one
for fruit in basket:
print(f"I love eating {fruit}")

# Iteration 1: fruit = "Apple"
# Iteration 2: fruit = "Banana"
# Iteration 3: fruit = "Mango"
# Loop Ends automatically.

🔢 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:

range(stop)

Starts at 0, goes up to (but NOT including) 'stop'.

range(3) -> 0, 1, 2
range(start, stop)

Starts at 'start', goes up to (but NOT including) 'stop'.

range(2, 5) -> 2, 3, 4
range(start, stop, step)

Starts at 'start', adds 'step' each time.

range(0, 10, 2) -> 0, 2, 4, 6, 8

💻 Example: The Countdown

# Counting down (Negative Step)
for i in range(5, 0, -1):
print(f"T-Minus {i}")
print("Blast off! 🚀")

📦 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

# Outer loop (X-axis)
for x in range(1, 4):
# Inner loop (Y-axis)
for y in range(1, 3):
print(f"Coordinate: ({x}, {y})")

# Output:
# Coordinate: (1, 1)
# Coordinate: (1, 2) <- Inner loop finished
# Coordinate: (2, 1) <- Outer loop moves to 2, Inner starts over
# Coordinate: (2, 2)

🚀 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.

colors = ["Red", "Green", "Blue"]

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().

scores = {"Vinay": 90, "Priya": 95}

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):