For Loops - Repeating Actions

A for loop is like a factory conveyor belt. Each item on the belt gets the same treatment. You put items on the belt once, and the machine processes each one automatically.
A **for loop** allows you to repeat a block of code for each item in a sequence. Instead of writing the same code multiple times, you write it once and Python executes it repeatedly – once for each element. This is called *iteration*.

**Basic syntax:**
```python
for variable in sequence:
# code to repeat
```
The `variable` takes the value of each item in the `sequence` one by one. The sequence can be a list, a string, a range of numbers, or any other iterable.

**The `range()` function:**
`range()` generates a sequence of numbers. Common forms:
- `range(stop)` – numbers from 0 to stop-1 (e.g., `range(5)` → 0,1,2,3,4)
- `range(start, stop)` – numbers from start to stop-1 (e.g., `range(2, 7)` → 2,3,4,5,6)
- `range(start, stop, step)` – numbers with a step (e.g., `range(1, 10, 2)` → 1,3,5,7,9)

**Looping through lists:**
```python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
```

**Looping through strings:**
Strings are sequences of characters:
```python
for char in "Python":
print(char) # P, y, t, h, o, n
```

**Getting both index and value with `enumerate()`:**
`enumerate()` returns pairs of (index, value):
```python
colors = ["red", "green", "blue"]
for i, color in enumerate(colors):
print(f"{i}: {color}")
```
Output:
```
0: red
1: green
2: blue
```

**Nested loops:**
You can put a loop inside another loop. The inner loop completes all its iterations for each iteration of the outer loop:
```python
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
```

**Loop control statements:**
- `break` – exits the loop immediately
- `continue` – skips the rest of the current iteration and moves to the next
- `else` – executes after the loop finishes normally (not if `break` occurred)

**Common use cases:**
- Processing each item in a list (e.g., calculating total, applying a discount)
- Generating multiplication tables
- Building patterns (pyramids, triangles) with repeated characters
- Reading lines from a file
- Repeating an action a fixed number of times

**Common mistakes:**
- Forgetting to indent the loop body
- Modifying a list while iterating over it (can cause unexpected behavior – use a copy or iterate backwards)
- Using the wrong variable name inside the loop
- Off‑by‑one errors with `range()` (remember `range(stop)` stops before `stop`)

**Performance tip:**
When you only need to iterate a fixed number of times without using the loop variable, use `_` as the variable name:
```python
for _ in range(5):
print("Hello") # prints 5 times
```

**Real‑world examples:**
- Processing a list of sales transactions to calculate total revenue
- Sending emails to a list of subscribers
- Generating a report from database rows
- Creating a menu system that displays each option
- Analyzing survey responses

**Practice exercises:**
1. Use a `for` loop to print all even numbers from 2 to 20.
2. Given a list of numbers, compute the sum using a loop (don't use `sum()`).
3. Print a 5×5 grid of `#` characters using nested loops.
4. Find the largest number in a list using a loop (don't use `max()`).
5. Create a list of the first 10 square numbers (1, 4, 9, …, 100) using a loop.
6. Given a string, count how many vowels (`a, e, i, o, u`) it contains.

**Example with `break` and `continue`:**
```python
for num in range(10):
if num == 3:
continue # skip 3
if num == 7:
break # stop at 7
print(num) # 0,1,2,4,5,6
```
# ========== EXAMPLE 1: Counting with range() ==========
print("=== Example 1: Counting from 1 to 5 ===")
for number in range(1, 6):   # 1 to 5 (6 is exclusive)
    print(number)
print()

# ========== EXAMPLE 2: Looping through a list and building a multiplication table ==========
print("=== Example 2: Looping Through Lists and Multiplication ===")
fruits = ["apple", "banana", "cherry", "date"]
print("My favorite fruits:")
for fruit in fruits:
    print(f"I love {fruit}")

print("\nMultiplication table for 5:")
for i in range(1, 11):   # 1 to 10
    result = 5 * i
    print(f"5 x {i} = {result}")
print()

# ========== EXAMPLE 3: enumerate() and pattern building ==========
print("=== Example 3: Index with enumerate() and Star Pattern ===")
colors = ["red", "green", "blue", "yellow"]
print("Colors with their positions:")
for index, color in enumerate(colors):
    print(f"Position {index}: {color}")

print("\nBuilding a right‑angle triangle pattern:")
for i in range(5):
    print("*" * (i + 1))

# Bonus: using break and continue
print("\n--- Break and Continue Demo ---")
for num in range(10):
    if num == 3:
        continue   # skip printing 3
    if num == 7:
        break      # stop the loop at 7
    print(num, end=" ")
print("\nLoop ended.")

→ Run this code interactively