> ## Documentation Index
> Fetch the complete documentation index at: https://rajanand.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Python Loops and Iterations

## 1. **What are Loops?**

* **Loops** are used to repeatedly execute a block of code.
* They are essential for automating repetitive tasks and iterating over sequences like lists, tuples, strings, etc.
* Python supports two types of loops:
  1. **`for` loops**
  2. **`while` loops**

## 2. **`for` Loop**

* The `for` loop is used to iterate over a sequence (e.g., list, tuple, string, range) or other iterable objects.
* Syntax:
  ```python theme={"system"}
  for item in sequence:
      # Code to execute
  ```

**Example**:

```python theme={"system"}
names = ["Raj", "Ram", "Anand", "Bala"]
for name in names:
    print(f"Hello, {name}!")
```

**Output**:

```
Hello, Raj!
Hello, Ram!
Hello, Anand!
Hello, Bala!
```

### **Using `range()` in `for` Loops**

* The `range()` function generates a sequence of numbers.
* It is commonly used to iterate a specific number of times.

**Example**:

```python theme={"system"}
for i in range(5):  # Iterates from 0 to 4
    print(i)
```

**Output**:

```
0
1
2
3
4
```

## 3. **`while` Loop**

* The `while` loop repeats a block of code as long as a condition is `True`.
* Syntax:
  ```python theme={"system"}
  while condition:
      # Code to execute
  ```

**Example**:

```python theme={"system"}
count = 0
while count < 5:
    print(f"Count: {count}")
    count += 1
```

**Output**:

```
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
```

## 4. **Loop Control Statements**

* These statements alter the flow of loops:
  1. **`break`**: Exits the loop immediately.
  2. **`continue`**: Skips the rest of the code in the current iteration and moves to the next iteration.
  3. **`pass`**: A placeholder for future code (does nothing).

**Examples**:

* **`break`**:

  ```python theme={"system"}
  for i in range(10):
      if i == 5:
          break  # Exit the loop when i is 5
      print(i)
  ```

  **Output**:

  ```
  0
  1
  2
  3
  4
  ```

* **`continue`**:

  ```python theme={"system"}
  for i in range(5):
      if i == 2:
          continue  # Skip the rest of the code for i = 2
      print(i)
  ```

  **Output**:

  ```
  0
  1
  3
  4
  ```

* **`pass`**:

  ```python theme={"system"}
  for i in range(3):
      if i == 1:
          pass  # Placeholder for future code
      print(i)
  ```

  **Output**:

  ```
  0
  1
  2
  ```

## 5. **Nested Loops**

* A loop inside another loop is called a **nested loop**.
* Commonly used for working with multi-dimensional data structures.

**Example**:

```python theme={"system"}
for i in range(3):  # Outer loop
    for j in range(2):  # Inner loop
        print(f"i={i}, j={j}")
```

**Output**:

```
i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1
```

## 6. **Iterating Over Sequences**

* Loops can iterate over various sequences like lists, tuples, strings, dictionaries, etc.

**Examples**:

* **List**:
  ```python theme={"system"}
  numbers = [10, 20, 30, 40]
  for num in numbers:
      print(num)
  ```

* **String**:
  ```python theme={"system"}
  name = "Karthik"
  for char in name:
      print(char)
  ```

* **Dictionary**:
  ```python theme={"system"}
  person = {"name": "Kumar", "age": 25, "city": "Chennai"}
  for key, value in person.items():
      print(f"{key}: {value}")
  ```

## 7. **Additional Examples**

* **`for` Loop**:
  ```python theme={"system"}
  names = ["Siva", "Ramesh", "Suresh", "Sathish"]
  for name in names:
      print(f"Welcome, {name}!")
  ```

* **`while` Loop**:
  ```python theme={"system"}
  count = 1
  while count <= 3:
      print(f"Attempt {count}")
      count += 1
  ```

* **Nested Loops**:
  ```python theme={"system"}
  for i in range(2):  # Outer loop
      for j in range(3):  # Inner loop
          print(f"i={i}, j={j}")
  ```

* **Loop Control**:
  ```python theme={"system"}
  for i in range(10):
      if i == 7:
          break  # Exit the loop when i is 7
      print(i)
  ```

## 8. **Best Practices**

* Use meaningful variable names for iterators (e.g., `name` instead of `x`).
* Avoid infinite loops in `while` loops by ensuring the condition eventually becomes `False`.
* Use `break` and `continue` sparingly to keep the code readable.
* Use list comprehensions for simple loops that create lists.

**Example**:

```python theme={"system"}
squares = [x ** 2 for x in range(5)]  # List comprehension
print(squares)  # Output: [0, 1, 4, 9, 16]
```
