#controlStructures #U3-AOS1 # Python For Loops In Python, a **for loop** is used to iterate over a sequence (like a list, tuple, dictionary, set, or string). Unlike other programming languages where a loop is often just a counter, the Python `for` loop works more like an **iterator**. It executes a set of statements once for each item in the sequence. ![[Pasted image 20260129130222.png]] ## 1. Basic Looping You do not need to create an indexing variable (like `i = 0`) beforehand. Python handles this automatically. ### Looping Through a List This will print every item inside the list `fruits`. ```python fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) ``` ### Looping Through a String Strings are also sequences (of characters), so you can loop through them just like a list. ```python for x in "banana": print(x) ``` --- ## 2. Controlling the Loop Sometimes you need to interrupt the standard flow of the loop. We use `break` and `continue` for this. ### The `break` Statement Stops the loop entirely. It "breaks out" of the loop. **Example 1: Break after printing** Here, the loop stops _after_ it prints "banana". Python ```python fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": break ``` **Example 2: Break before printing** Here, the loop stops _before_ it prints "banana", so "banana" is never shown. ```python fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": break print(x) ``` ### The `continue` Statement Stops only the **current iteration** and jumps to the next item in the list. **Example:** Skip "banana" but keep going to "cherry". ```python fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue # Skip the rest of the code for this item print(x) ``` --- ## 3. The `range()` Function If you need to loop a specific number of times rather than through a specific list, use `range()`. It generates a sequence of numbers. > **Important Note:** The `range()` function is **exclusive** of the end number. `range(6)` means 0 to 5, not 0 to 6. ### Three Ways to Use `range()` |Syntax|Description|Example|Result| |---|---|---|---| |**`range(stop)`**|Starts at 0, increments by 1.|`range(6)`|0, 1, 2, 3, 4, 5| |**`range(start, stop)`**|Starts at `start`, increments by 1.|`range(2, 6)`|2, 3, 4, 5| |**`range(start, stop, step)`**|Starts at `start`, increments by `step`.|`range(2, 30, 3)`|2, 5, 8, ... 29| **Example Code:** ```python for x in range(2, 30, 3): print(x) ``` --- ## 4. Advanced Loop Features ### `Else` in For Loop Uniquely, Python allows an `else` block after a loop. It runs **only if the loop finishes successfully** (i.e., it was NOT stopped by a `break`). ```python for x in range(6): print(x) else: print("Finally finished!") ``` _If you use a `break` inside the loop, the `else` block is skipped._ ### Nested Loops A "loop inside a loop". The inner loop executes one full cycle for **every single iteration** of the outer loop. ```python adj = ["red", "big", "tasty"] fruits = ["apple", "banana", "cherry"] for x in adj: # Outer loop for y in fruits: # Inner loop print(x, y) ``` ### The `pass` Statement Loops cannot be empty in Python syntax. If you are writing code and want to leave a loop empty temporarily (as a placeholder), use `pass` to avoid an error. ```python for x in [0, 1, 2]: pass ``` # Review questions **1. Which of the following is the correct syntax for a basic `for` loop in Python?** - A) `for i in 10:` - B) `for i in range(10):` - C) `for (i=0; i<10; i++):` - D) `for range(10) as i:` **2. What does the `range(5)` function actually produce?** - A) 1, 2, 3, 4, 5 - B) 0, 1, 2, 3, 4, 5 - C) 0, 1, 2, 3, 4 - D) 5, 5, 5, 5, 5 **3. In the line `for color in ["red", "blue", "green"]:`, what is the variable `color` called?** - A) The loop constant - B) The range - C) The loop variable (or iterator) - D) The list index **4. What will be printed when the following code runs?** ```python total = 0 for i in range(4): total = total + i print(total) ``` - _Hint: Remember that range starts at 0._ **5. What is the output of this loop?** ```python words = ["Apple", "Banana", "Cherry"] for w in words: if len(w) > 5: print(w) ``` **6. Find the Error:** The following code is supposed to print "Hello" 5 times, but it has two errors. Can you find them? ```python for x in range(5) print("Hello") ```