> For the complete documentation index, see [llms.txt](https://py.d19.in/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://py.d19.in/chapter-3-control-flow.md).

# Chapter 3: Control Flow

***

### 1. **Conditional Statements**

Conditional statements execute different code blocks based on conditions.

#### 1.1 **`if` Statement**

The simplest form of control flow. If a condition is `True`, the code inside the `if` block is executed.

Syntax:

```python
if condition:
    # Code to execute if the condition is True
```

Example:

```python
age = 18
if age >= 18:
    print("You are an adult.")
```

***

#### 1.2 **`if-else` Statement**

Provides an alternative code block if the condition is `False`.

Syntax:

```python
if condition:
    # Code to execute if the condition is True
else:
    # Code to execute if the condition is False
```

Example:

```python
num = 10
if num % 2 == 0:
    print("Even number.")
else:
    print("Odd number.")
```

***

#### 1.3 **`if-elif-else` Statement**

Tests multiple conditions in sequence.

Syntax:

```python
if condition1:
    # Code if condition1 is True
elif condition2:
    # Code if condition2 is True
else:
    # Code if none of the above conditions are True
```

Example:

```python
score = 85
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
else:
    print("Grade: C")
```

***

#### 1.4 Nested `if` Statements

`if` statements can be nested for more complex conditions.

Example:

```python
age = 20
has_id = True

if age >= 18:
    if has_id:
        print("Access granted.")
    else:
        print("ID required.")
else:
    print("Access denied.")
```

***

#### 1.5 Ternary Conditional Expression

A one-liner for `if-else` statements.

Syntax:

```python
value = true_value if condition else false_value
```

Example:

```python
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)
```

***

#### 1.6 Precautions with Conditionals

1. **Proper Indentation**: Python relies on indentation to define blocks. A mismatch will cause errors.
2. **Avoid Overcomplicating**: Use `elif` instead of nesting multiple `if` statements.
3. **Boolean Values**: Avoid redundancy. For example, instead of:

   ```python
   if x == True:
   ```

   Simply use:

   ```python
   if x:
   ```

***

### 2. **Loops**

Loops allow you to execute code repeatedly.

#### 2.1 **`while` Loop**

Repeats as long as a condition is `True`.

Syntax:

```python
while condition:
    # Code to execute repeatedly
```

Example:

```python
count = 0
while count < 5:
    print(count)
    count += 1
```

**Precautions:**

* **Infinite Loops**: Ensure the condition eventually becomes `False`.
* Use a `break` statement to exit loops if necessary.

***

#### 2.2 **`for` Loop**

Iterates over a sequence (e.g., list, string, range).

Syntax:

```python
for variable in sequence:
    # Code to execute for each item in the sequence
```

Example:

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

***

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

The `range()` function generates a sequence of numbers, commonly used in `for` loops.

Examples:

```python
for i in range(5):  # 0 to 4
    print(i)

for i in range(2, 10, 2):  # Start at 2, end at 9, step by 2
    print(i)
```

***

#### 2.4 **`break` and `continue`**

* **`break`**: Exit the loop entirely.
* **`continue`**: Skip to the next iteration.

Examples:

```python
for i in range(5):
    if i == 3:
        break
    print(i)  # Stops when i == 3

for i in range(5):
    if i == 2:
        continue
    print(i)  # Skips i == 2
```

***

#### 2.5 Nested Loops

Loops inside other loops.

Example:

```python
for i in range(3):
    for j in range(2):
        print(f"i={i}, j={j}")
```

***

### 3. **Control Flow Tools**

#### 3.1 The `pass` Statement

Does nothing; acts as a placeholder.

Example:

```python
if True:
    pass  # Placeholder for future code
```

***

#### 3.2 The `else` Clause in Loops

A `for` or `while` loop can have an `else` clause. The `else` block runs if the loop completes normally (i.e., no `break`).

Example:

```python
for i in range(5):
    if i == 3:
        break
else:
    print("Loop completed.")
```

***

### 4. **Comprehensions**

#### 4.1 List Comprehensions

A concise way to create lists.

Example:

```python
squares = [x**2 for x in range(5)]
print(squares)  # [0, 1, 4, 9, 16]
```

#### 4.2 Dictionary Comprehensions

Create dictionaries in one line.

Example:

```python
squared_dict = {x: x**2 for x in range(5)}
print(squared_dict)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
```

***

### 5. **Precautions and Tricks**

1. **Avoid Infinite Loops**:
   * Always ensure the loop condition will eventually be `False`.
2. **Keep Logic Simple**:
   * Use comprehensions where possible for clarity and efficiency.
3. **Don’t Modify a Collection While Iterating**:
   * If you need to modify a list while looping, iterate over a copy:

     ```python
     for item in list(items):
         items.remove(item)
     ```
4. **`else` in Loops**:
   * Remember that the `else` block executes **only if the loop wasn't terminated by `break`**.

***

### Summary Table: Control Flow Tools

| Control Flow Tool | Description                             | Example                            |
| ----------------- | --------------------------------------- | ---------------------------------- |
| `if`              | Executes block if condition is `True`.  | `if x > 5: print(x)`               |
| `if-else`         | Adds an alternative block.              | `if x > 5: ... else: ...`          |
| `if-elif-else`    | Tests multiple conditions.              | `if x > 5: ... elif x == 5: ...`   |
| `while`           | Repeats as long as condition is `True`. | `while x < 5: ...`                 |
| `for`             | Iterates over a sequence.               | `for item in list: ...`            |
| `break`           | Exits the loop entirely.                | `if x == 3: break`                 |
| `continue`        | Skips to the next iteration.            | `if x == 3: continue`              |
| `pass`            | Does nothing (placeholder).             | `if x > 5: pass`                   |
| `else` in loops   | Executes if loop completes normally.    | `for x in range(5): ... else: ...` |
| Comprehensions    | One-line list or dict creation.         | `[x**2 for x in range(5)]`         |

***
