Conditional statements control program execution paths based on boolean evaluations (if, elif, else). Python 3.10+ also introduces structural pattern matching (match/case) for complex data destructuring.
flowchart TD
A["Start Evaluation"] --> B{"Condition 1 True?"}
B -- "Yes" --> C["Execute If Block"]
B -- "No" --> D{"Condition 2 True?"}
D -- "Yes" --> E["Execute Elif Block"]
D -- "No" --> F["Execute Else Block"]
C --> G["Continue Program Execution"]
E --> G
F --> G
if condition: ... elif condition: ... else: ...value = true_val if condition else false_valmatch subject: case pattern: ...from typing import Any, Dict
def handle_http_status(status_code: int) -> str:
"""Demonstrate Python 3.10+ Structural Pattern Matching."""
match status_code:
case 200 | 201:
return "Success: Resource processed."
case 400:
return "Client Error: Bad Request."
case 401 | 403:
return "Security Alert: Unauthorized or Forbidden."
case 404:
return "Client Error: Resource Not Found."
case 500 | 502 | 503:
return "Server Error: Internal system failure."
case _:
return f"Unhandled Status Code: {status_code}"
def evaluate_discount(user_score: int, is_vip: bool) -> float:
# Ternary Conditional Operator
discount_rate = 0.20 if is_vip or user_score >= 100 else 0.05
return discount_rate
if __name__ == "__main__":
print(handle_http_status(200))
print(handle_http_status(404))
print(handle_http_status(999))
rate = evaluate_discount(120, False)
print(f"Applicable Discount Rate: {rate * 100}%")
if statements. Return early (guard clause) to keep code readable.match/case when matching data structures, types, or enumerations; use if/elif for range checks (x > 50).if x = 5: (SyntaxError). Use the walrus operator if (x := 5) > 2: if intentional.Write a function categorize_age(age: int) -> str using if/elif/else that returns "Minor" (age < 18), "Adult" (18 <= age < 65), or "Senior" (age >= 65).
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With