Selection in Python

Selection in Python refers to the use of conditional statements to control the flow of a program based on specific conditions. The primary keywords used are `if`, `elif` (short for "else if"), and `else`.

---

 **1. Basic `if` Statement**
- Executes a block of code **only if** a condition is `True`.
- **Syntax**:
  ```python
  if condition:
      # code to execute if condition is True
  ```

**Example**:
```python
num = 10
if num > 0:
    print("Positive number")
```

---
 **2. `if-else` Statement**
- Executes one block if a condition is `True`, and another block if it is `False`.
- **Syntax**:
  ```python
  if condition:
      # code if True
  else:
      # code if False
  ```

**Example**:
```python
num = -5
if num >= 0:
    print("Non-negative")
else:
    print("Negative")
```

---

 **3. `if-elif-else` Statement**
- Checks multiple conditions in sequence. Stops at the first `True` condition.
- **Syntax**:
  ```python
  if condition1:
      # code if condition1 is True
  elif condition2:
      # code if condition2 is True
  else:
      # code if all conditions are False
  ```

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

---

**4. Nested `if` Statements**
- An `if` statement inside another `if`, `elif`, or `else` block.
- **Example**:
  ```python
  age = 25
  is_citizen = True

  if age >= 18:
      if is_citizen:
          print("Eligible to vote")
      else:
          print("Not a citizen")
  else:
      print("Too young to vote")
  ```

---
 **5. Ternary Operator**
- A shorthand for simple `if-else` conditions in a single line.
- **Syntax**:
  ```python
  value = x if condition else y
  ```

**Example**:
```python
num = 7
parity = "Even" if num % 2 == 0 else "Odd"
print(parity)  # Output: Odd
```

---
 **6. Logical Operators (`and`, `or`, `not`)**
- Combine multiple conditions:
  - `and`: Both conditions must be `True`.
  - `or`: At least one condition must be `True`.
  - `not`: Inverts the result of a condition.

**Example**:
```python
temperature = 22
humidity = 65

if temperature > 20 and humidity < 70:
    print("Comfortable weather")
```

---

 **7. Truthy and Falsy Values**
- In Python, non-boolean values are evaluated in a Boolean context:
  - **Falsy**: `0`, `""`, `None`, empty containers (`[]`, `{}`, `()`).
  - **Truthy**: Any non-zero number, non-empty strings, non-empty containers.

**Example**:
```python
name = ""
if not name:
    print("Name is empty")
```

---

 **8. Common Mistakes**
- **Using `=` instead of `==`**:
  ```python
  if x = 5:  # SyntaxError (use == for comparison)
  ```
- **Missing Colons**:
  ```python
  if x > 0  # SyntaxError (missing colon)
  ```
- **Incorrect Indentation**: Python uses indentation to define code blocks.

---

 **9. `match-case` (Python 3.10+)**
- Structural pattern matching for complex conditions (similar to `switch-case` in other languages).
- **Example**:
  ```python
  day = "Mon"
  match day:
      case "Mon" | "Tue" | "Wed" | "Thu" | "Fri":
          print("Weekday")
      case "Sat" | "Sun":
          print("Weekend")
      case _:
          print("Invalid day")
  ```

---
 **Key Takeaways**
- Use `if`, `elif`, and `else` to handle different conditions.
- Combine conditions with `and`, `or`, and `not`.
- Use `pass` as a placeholder for empty blocks:
  ```python
  if x > 0:
      pass  # Do nothing
  else:
      print("Negative")
  ```

Selection structures are fundamental for creating dynamic and responsive programs in Python.

Comments

Popular posts from this blog

Kotlin Math Operations and Functions Overview

Wear OS Android UI Application in Kotlin

Kotlin Android Program (QCR) Application Codes That Read Text in Photos