Posts

Showing posts with the label Iteration in Python

Iteration in Python

 Iteration in Python allows you to execute a block of code repeatedly. Below are the key methods and constructs used for iteration: --- **1. `for` Loop** Iterates over items in an iterable (e.g., lists, tuples, strings, dictionaries).   **Syntax**: ```python for item in iterable:     # Code block ``` **Example**: ```python fruits = ["apple", "banana", "cherry"] for fruit in fruits:     print(fruit) ``` **Using `range()`** (for numerical ranges): ```python for i in range(5):  # 0 to 4     print(i) ``` --- **2. `while` Loop** Repeats code while a condition is `True`.   **Syntax**: ```python while condition:     # Code block ``` **Example**: ```python count = 3 while count > 0:     print(count)     count -= 1  # Output: 3, 2, 1 ``` **Avoid Infinite Loops**: Ensure the condition eventually becomes `False`. --- **3. Iterables vs. Iterators** - **Iterable**: An object that can return an iterator ...