|
| 1 | +--- |
| 2 | +id: python-loops |
| 3 | +title: Loops in Python |
| 4 | +sidebar_label: Loops in Python |
| 5 | +sidebar_position: 10 |
| 6 | +tags: |
| 7 | + - Python |
| 8 | + - Loops |
| 9 | + - for loop |
| 10 | + - while loop |
| 11 | + - Control Flow |
| 12 | + - Iteration |
| 13 | + - Python Syntax |
| 14 | +--- |
| 15 | + |
| 16 | +# Loops in Python |
| 17 | + |
| 18 | +Loops in Python allow you to execute a block of code repeatedly. They are essential for automating repetitive tasks and processing collections of data efficiently. |
| 19 | + |
| 20 | +## The `for` Loop |
| 21 | + |
| 22 | +The `for` loop is used to iterate over a sequence (like a list, tuple, string, or range). |
| 23 | + |
| 24 | +**Syntax:** |
| 25 | + |
| 26 | +```python |
| 27 | +for variable in sequence: |
| 28 | + # block of code |
| 29 | +``` |
| 30 | + |
| 31 | +**Example:** |
| 32 | + |
| 33 | +```python |
| 34 | +fruits = ["apple", "banana", "cherry"] |
| 35 | +for fruit in fruits: |
| 36 | + print(fruit) |
| 37 | +``` |
| 38 | + |
| 39 | +**Output:** |
| 40 | +``` |
| 41 | +apple |
| 42 | +banana |
| 43 | +cherry |
| 44 | +``` |
| 45 | + |
| 46 | +## The `range()` Function |
| 47 | + |
| 48 | +The `range()` function generates a sequence of numbers, commonly used with `for` loops. |
| 49 | + |
| 50 | +```python |
| 51 | +# Print numbers 0 to 4 |
| 52 | +for i in range(5): |
| 53 | + print(i) |
| 54 | + |
| 55 | +# Print numbers 2 to 6 |
| 56 | +for i in range(2, 7): |
| 57 | + print(i) |
| 58 | + |
| 59 | +# Print even numbers from 0 to 8 |
| 60 | +for i in range(0, 10, 2): |
| 61 | + print(i) |
| 62 | +``` |
| 63 | + |
| 64 | +**Output:** |
| 65 | +``` |
| 66 | +0 |
| 67 | +1 |
| 68 | +2 |
| 69 | +3 |
| 70 | +4 |
| 71 | +``` |
| 72 | + |
| 73 | +## The `while` Loop |
| 74 | + |
| 75 | +The `while` loop continues executing as long as a condition is **True**. |
| 76 | + |
| 77 | +**Syntax:** |
| 78 | + |
| 79 | +```python |
| 80 | +while condition: |
| 81 | + # block of code |
| 82 | +``` |
| 83 | + |
| 84 | +**Example:** |
| 85 | + |
| 86 | +```python |
| 87 | +count = 1 |
| 88 | +while count <= 5: |
| 89 | + print(f"Count: {count}") |
| 90 | + count += 1 |
| 91 | +``` |
| 92 | + |
| 93 | +**Output:** |
| 94 | +``` |
| 95 | +Count: 1 |
| 96 | +Count: 2 |
| 97 | +Count: 3 |
| 98 | +Count: 4 |
| 99 | +Count: 5 |
| 100 | +``` |
| 101 | + |
| 102 | +## Loop Control Statements |
| 103 | + |
| 104 | +### The `break` Statement |
| 105 | + |
| 106 | +`break` exits the loop immediately. |
| 107 | + |
| 108 | +```python |
| 109 | +for i in range(10): |
| 110 | + if i == 5: |
| 111 | + break |
| 112 | + print(i) |
| 113 | +``` |
| 114 | + |
| 115 | +**Output:** |
| 116 | +``` |
| 117 | +0 |
| 118 | +1 |
| 119 | +2 |
| 120 | +3 |
| 121 | +4 |
| 122 | +``` |
| 123 | + |
| 124 | +### The `continue` Statement |
| 125 | + |
| 126 | +`continue` skips the current iteration and moves to the next one. |
| 127 | + |
| 128 | +```python |
| 129 | +for i in range(5): |
| 130 | + if i == 2: |
| 131 | + continue |
| 132 | + print(i) |
| 133 | +``` |
| 134 | + |
| 135 | +**Output:** |
| 136 | +``` |
| 137 | +0 |
| 138 | +1 |
| 139 | +3 |
| 140 | +4 |
| 141 | +``` |
| 142 | + |
| 143 | +### The `pass` Statement |
| 144 | + |
| 145 | +`pass` is a placeholder that does nothing. Useful when you need syntactically correct code but no action. |
| 146 | + |
| 147 | +```python |
| 148 | +for i in range(3): |
| 149 | + if i == 1: |
| 150 | + pass # Do nothing for i == 1 |
| 151 | + else: |
| 152 | + print(i) |
| 153 | +``` |
| 154 | + |
| 155 | +## Nested Loops |
| 156 | + |
| 157 | +You can place one loop inside another loop. |
| 158 | + |
| 159 | +```python |
| 160 | +# Multiplication table |
| 161 | +for i in range(1, 4): |
| 162 | + for j in range(1, 4): |
| 163 | + print(f"{i} x {j} = {i * j}") |
| 164 | + print() # Empty line after each row |
| 165 | +``` |
| 166 | + |
| 167 | +**Output:** |
| 168 | +``` |
| 169 | +1 x 1 = 1 |
| 170 | +1 x 2 = 2 |
| 171 | +1 x 3 = 3 |
| 172 | +
|
| 173 | +2 x 1 = 2 |
| 174 | +2 x 2 = 4 |
| 175 | +2 x 3 = 6 |
| 176 | +
|
| 177 | +3 x 1 = 3 |
| 178 | +3 x 2 = 6 |
| 179 | +3 x 3 = 9 |
| 180 | +``` |
| 181 | + |
| 182 | +## Looping Through Different Data Types |
| 183 | + |
| 184 | +### Strings |
| 185 | + |
| 186 | +```python |
| 187 | +word = "Python" |
| 188 | +for letter in word: |
| 189 | + print(letter) |
| 190 | +``` |
| 191 | + |
| 192 | +### Dictionaries |
| 193 | + |
| 194 | +```python |
| 195 | +student = {"name": "Alice", "age": 20, "grade": "A"} |
| 196 | + |
| 197 | +# Loop through keys |
| 198 | +for key in student: |
| 199 | + print(key) |
| 200 | + |
| 201 | +# Loop through values |
| 202 | +for value in student.values(): |
| 203 | + print(value) |
| 204 | + |
| 205 | +# Loop through key-value pairs |
| 206 | +for key, value in student.items(): |
| 207 | + print(f"{key}: {value}") |
| 208 | +``` |
| 209 | + |
| 210 | +### Lists with Index |
| 211 | + |
| 212 | +```python |
| 213 | +colors = ["red", "green", "blue"] |
| 214 | + |
| 215 | +# Using enumerate() to get index and value |
| 216 | +for index, color in enumerate(colors): |
| 217 | + print(f"{index}: {color}") |
| 218 | +``` |
| 219 | + |
| 220 | +**Output:** |
| 221 | +``` |
| 222 | +0: red |
| 223 | +1: green |
| 224 | +2: blue |
| 225 | +``` |
| 226 | + |
| 227 | +## The `else` Clause in Loops |
| 228 | + |
| 229 | +Loops can have an `else` clause that executes when the loop completes normally (not broken by `break`). |
| 230 | + |
| 231 | +```python |
| 232 | +# With for loop |
| 233 | +for i in range(3): |
| 234 | + print(i) |
| 235 | +else: |
| 236 | + print("Loop completed!") |
| 237 | + |
| 238 | +# With while loop |
| 239 | +count = 0 |
| 240 | +while count < 3: |
| 241 | + print(count) |
| 242 | + count += 1 |
| 243 | +else: |
| 244 | + print("While loop finished!") |
| 245 | +``` |
| 246 | + |
| 247 | +## Common Loop Patterns |
| 248 | + |
| 249 | +### Counting Pattern |
| 250 | + |
| 251 | +```python |
| 252 | +# Count occurrences |
| 253 | +text = "hello world" |
| 254 | +count = 0 |
| 255 | +for char in text: |
| 256 | + if char == 'l': |
| 257 | + count += 1 |
| 258 | +print(f"Letter 'l' appears {count} times") |
| 259 | +``` |
| 260 | + |
| 261 | +### Accumulation Pattern |
| 262 | + |
| 263 | +```python |
| 264 | +# Sum of numbers |
| 265 | +numbers = [1, 2, 3, 4, 5] |
| 266 | +total = 0 |
| 267 | +for num in numbers: |
| 268 | + total += num |
| 269 | +print(f"Sum: {total}") |
| 270 | +``` |
| 271 | + |
| 272 | +### Finding Pattern |
| 273 | + |
| 274 | +```python |
| 275 | +# Find first even number |
| 276 | +numbers = [1, 3, 5, 8, 9, 10] |
| 277 | +for num in numbers: |
| 278 | + if num % 2 == 0: |
| 279 | + print(f"First even number: {num}") |
| 280 | + break |
| 281 | +``` |
| 282 | + |
| 283 | +## Best Practices |
| 284 | + |
| 285 | +1. **Use `for` loops** when you know the number of iterations |
| 286 | +2. **Use `while` loops** when the condition determines when to stop |
| 287 | +3. **Avoid infinite loops** by ensuring the condition eventually becomes `False` |
| 288 | +4. **Use meaningful variable names** in loops |
| 289 | +5. **Consider list comprehensions** for simple transformations |
| 290 | + |
| 291 | +## Summary Table |
| 292 | + |
| 293 | +| Loop Type | Use Case | |
| 294 | +|------------------------|---------------------------------------------| |
| 295 | +| `for` loop | Iterating over sequences (lists, strings) | |
| 296 | +| `while` loop | Repeating until a condition is met | |
| 297 | +| `break` | Exit loop immediately | |
| 298 | +| `continue` | Skip current iteration | |
| 299 | +| `pass` | Placeholder for empty loop body | |
| 300 | +| Nested loops | Working with multi-dimensional data | |
| 301 | +| List comprehensions | Creating lists with concise syntax | |
| 302 | + |
| 303 | +## Conclusion |
| 304 | + |
| 305 | +Loops are fundamental to programming in Python. Whether you're processing data, automating tasks, or building complex algorithms, mastering `for` and `while` loops will make your code more efficient and powerful. Practice with different data types and loop patterns to become proficient in using loops effectively. |
0 commit comments