> For the complete documentation index, see [llms.txt](https://sai11101989.gitbook.io/iss_workbook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://sai11101989.gitbook.io/iss_workbook/object-oriented-programming/python-conditions-and-loops.md).

# Python - Conditions and Loops

## If and Else

In Python, conditional statements are fundamental for controlling the flow of a program based on certain conditions. The primary types of conditional statements include:

### Types of Conditional Statements in Python

1. **If Statement**
   * The simplest form of a conditional statement that executes a block of code if a specified condition is true.
   * **Syntax:**

     ```python
     if condition:
         # code to execute if condition is true
     ```
   * **Example:**

     ```python
     num = 8
     if num > 0:
         print("The number is positive.")
     ```
   * This code prints "The number is positive" if `num` is greater than zero.
2. **If-Else Statement**
   * This statement provides an alternative code block that executes when the condition in the `if` statement evaluates to false.
   * **Syntax:**

     ```python
     if condition:
         # code to execute if condition is true
     else:
         # code to execute if condition is false
     ```
   * **Example:**

     ```python
     num = 11
     if num % 2 == 0:
         print("The number is even.")
     else:
         print("The number is odd.")
     ```
   * This code checks if `num` is even or odd and prints the corresponding message.
3. **Nested If-Else Statement**
   * This allows one `if` statement to be placed inside another, enabling complex decision-making.
   * **Syntax:**

     ```python
     if condition1:
         if condition2:
             # code for both conditions being true
         else:
             # code for condition1 true, condition2 false
     else:
         # code for condition1 false
     ```
   * **Example:**

     ```python
     num = 3
     if num > 0:
         if num % 2 == 0:
             print("The number is positive and even.")
         else:
             print("The number is positive but odd.")
     else:
         print("The number is not positive.")
     ```
   * This checks multiple conditions about the variable `num`.
4. **If-Elif-Else Ladder**
   * This structure allows checking multiple expressions for truth and executing a block of code as soon as one of the conditions evaluates to true.
   * **Syntax:**

     ```python
     if condition1:
         # code block 1
     elif condition2:
         # code block 2
     elif condition3:
         # code block 3
     else:
         # default code block
     ```
   * **Example:**

     ```python
     x = 11
     if x == 2:
         print("x is equal to 2")
     elif x == 3:
         print("x is equal to 3")
     elif x == 4:
         print("x is equal to 4")
     else:
         print("x is not equal to 2, 3, or 4")
     ```
   * This allows for multiple conditions to be checked sequentially.
5. **Ternary Operator (Conditional Expressions)**
   * A shorthand way to write simple `if-else` statements in a single line.
   * **Syntax:**

     ```python
     value_if_true if condition else value_if_false
     ```
   * **Example:**

     ```python
     result = 'pass' if grade >= 50 else 'fail'
     print(result)
     ```
   * This assigns 'pass' or 'fail' based on the value of `grade`.

These various forms of conditional statements allow Python programmers to implement complex logic and control the flow of their programs effectively.

## While loop

Python has one primary type of `while` loop, but it can be used with several control statements to modify its behavior.

**Types of `while` Loops**

* **Basic `while` Loop**: This loop executes a block of code as long as a specified condition is true. The condition is checked at the beginning of each iteration.
  * **Syntax:**

    ```python
    while condition:
        # Code to execute
    ```
  * **Example:**

    ```python
    i = 1
    while i < 6:
        print(i)
        i += 1
    ```

    In this example, the loop prints the value of `i` as long as `i` is less than 6.

**Control Statements in `while` Loops**

* **`break` Statement**: This statement is used to exit the loop prematurely, even if the condition is still true.
  * **Example:**

    ```python
    i = 1
    while i < 6:
        print(i)
        if i == 3:
            break
        i += 1
    ```

    In this case, the loop will stop when `i` equals 3.
* **`continue` Statement**: This statement skips the rest of the current iteration and proceeds to the next iteration of the loop.
  * **Example:**

    ```python
    i = 0
    while i < 6:
        i += 1
        if i == 3:
            continue
        print(i)
    ```

    Here, when `i` is 3, the `print(i)` statement is skipped, and the loop continues with `i = 4`.
* **`else` Statement**: This block of code is executed when the loop condition becomes false. If the loop is terminated by a `break` statement, the `else` block is not executed.
  * **Example:**

    ```python
    pythoni = 1
    while i < 6:
        print(i)
        i += 1
    else:
        print("i is no longer less than 6")
    ```

    The `else` block will be executed once `i` is no longer less than 6.

**Other variations**

* **Infinite Loops**: These occur when the loop condition never becomes false. They can be useful in certain situations, but it is important to ensure there is a way to exit the loop (e.g., using a `break` statement).
  * **Example:**

    ```python
    while True:
        # Code to execute
        if some_condition:
            break
    ```
* **Nested `while` Loops**: You can place one `while` loop inside another, allowing for more complex control flow.
* **One-Line `while` Loops**: If the `while` loop contains simple statements, it can be written on a single line, with statements separated by semicolons.
  * **Example:**

    ```python
    n = 5
    while n > 0: n -= 1; print(n)
    ```

## For loop

In Python, the `for` loop is a versatile control structure used primarily for iterating over sequences such as lists, tuples, sets, dictionaries, and strings. Here are the main types and features of `for` loops in Python:

### Types of `for` Loops in Python

1. **Basic `for` Loop**
   * This loop iterates over a sequence (like a list or string) and executes a block of code for each item.
   * **Syntax:**

     ```python
     for variable in sequence:
         # Code to execute
     ```
   * **Example:**

     ```python
     fruits = ['apple', 'banana', 'cherry']
     for fruit in fruits:
         print(fruit)
     ```
   * This code will print each fruit in the list.
2. **`for` Loop with `range()`**
   * The `range()` function generates a sequence of numbers, which can be used to iterate a specific number of times.
   * **Syntax:**

     ```python
     for i in range(start, stop, step):
         # Code to execute
     ```
   * **Example:**

     ```python
     for i in range(1, 5):
         print(i)
     ```
   * This will print numbers from 1 to 4.
3. **Nested `for` Loops**
   * A `for` loop can be placed inside another `for` loop, allowing for iteration over multi-dimensional data structures.
   * **Syntax:**

     ```python
     for outer_variable in outer_sequence:
         for inner_variable in inner_sequence:
             # Code to execute
     ```
   * **Example:**

     ```python
     matrix = [[1, 2, 3], [4, 5, 6]]
     for row in matrix:
         for item in row:
             print(item)
     ```
   * This code will print each item in the two-dimensional list.
4. **List Comprehensions**
   * A concise way to create lists using a single line of code that includes a `for` loop.
   * **Syntax:**

     ```python
     new_list = [expression for item in iterable]
     ```
   * **Example:**

     ```python
     squares = [x**2 for x in range(10)]
     print(squares)
     ```
   * This creates a list of squares from 0 to 9.
5. **Iterating Over Dictionaries**
   * You can iterate through keys, values, or key-value pairs in a dictionary using a `for` loop.
   * **Example:**

     ```python
     my_dict = {'a': 1, 'b': 2, 'c': 3}
     for key, value in my_dict.items():
         print(key, value)
     ```
   * This will print each key-value pair in the dictionary.
6. **Using `break` and `continue` Statements**
   * The `break` statement can be used to exit the loop prematurely, while the `continue` statement skips the current iteration and moves to the next one.
   * **Example with `break`:**

     ```python
     for i in range(10):
         if i == 5:
             break
         print(i)
     ```
   * This prints numbers from 0 to 4 and then exits the loop when `i` equals 5.
   * **Example with `continue`:**

     ```python
     for i in range(5):
         if i == 2:
             continue
         print(i)
     ```
   * This prints numbers from 0 to 4 but skips printing the number 2.
