YouTip LogoYouTip

Python3 Elif Statement

## Python elif Statement In Python, `elif` is a keyword used for multi-way conditional branching. Short for **"else if"**, it allows you to chain multiple conditional checks together when you need to handle more than two distinct outcomes. Using `elif` prevents deeply nested `if-else` blocks, keeping your code clean, readable, and highly structured. --- ## Syntax and Execution Flow The `elif` statement must always be paired with an initial `if` statement. It cannot exist on its own. ### Syntax Structure ```python if condition_1: # Executed if condition_1 is True code_block_1 elif condition_2: # Executed if condition_1 is False AND condition_2 is True code_block_2 elif condition_3: # Executed if previous conditions are False AND condition_3 is True code_block_3 else: # Executed if all above conditions are False code_block_4 ``` ### Key Rules of Execution * **Sequential Evaluation**: Python evaluates conditions from top to bottom. The moment it encounters a condition that evaluates to `True`, it executes the corresponding code block and immediately exits the entire `if-elif-else` chain. Any remaining conditions are ignored. * **Unlimited Branches**: You can chain as many `elif` statements as your logic requires. * **Optional Else**: The final `else` block is optional. It acts as a catch-all fallback that executes only if none of the preceding `if` or `elif` conditions are met. --- ## Practical Examples ### Example 1: Basic Multi-Condition Grading System This example demonstrates how to categorize a numerical score into a letter grade using sequential range checks. ```python # Grading system score = 85 if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" elif score >= 60: grade = "D" else: grade = "F" print(f"Grade: {grade}") # Output: Grade: B ``` **Expected Output:** ```text Grade: B ``` **How it works:** 1. `score` is initialized to `85`. 2. Python checks the first condition: `score >= 90` (evaluates to `False`). 3. It moves to the first `elif`: `score >= 80` (evaluates to `True`). 4. The variable `grade` is set to `"B"`. 5. Python skips all subsequent `elif` and `else` blocks and jumps straight to the `print()` statement. --- ### Example 2: String Matching for Menu Selection `elif` is highly effective for handling user input or menu-driven command selections. ```python # Simple menu selection choice = "2" if choice == "1": print("You selected: Create New File") elif choice == "2": print("You selected: Open File") elif choice == "3": print("You selected: Save File") elif choice == "4": print("You selected: Exit") else: print("Invalid selection") ``` **Expected Output:** ```text You selected: Open File ``` **How it works:** * The program compares the string variable `choice` against multiple options. * Because each option is mutually exclusive, only the block corresponding to `"2"` is executed. --- ### Example 3: Combining Multiple Logical Operators You can combine multiple conditions within an `elif` statement using logical operators like `and` and `or`. ```python # Multi-condition evaluation using logical operators age = 25 income = 5000 if age < 18: print("Minor") elif age >= 18 and income < 3000: print("Adult, Low Income") elif age >= 18 and income >= 3000 and income < 10000: print("Adult, Middle Income") elif age >= 18 and income >= 10000: print("Adult, High Income") # Using elif to handle application status codes cleanly status = "error" if status == "success": print("Operation successful") elif status == "error": print("Operation failed") elif status == "warning": print("Warning issued") elif status == "info": print("Information message") ``` **Expected Output:** ```text Adult, Middle Income Operation failed ``` --- ## Best Practices and Considerations 1. **Order Matters**: Always place your most specific conditions at the top and the most general conditions at the bottom. If a general condition is placed first, it might intercept values meant for a more specific branch. 2. **Avoid Redundancy**: If you are checking mutually exclusive ranges (like in Example 1), you do not need to write complex compound conditions like `elif score >= 80 and score < 90:`. Since the `score >= 90` check already failed in the previous step, you can safely write `elif score >= 80:`. 3. **Alternative for Python 3.10+**: If you are matching variables against specific constant values (like in Example 2), consider using Python's modern `match-case` statement (structural pattern matching) for even cleaner syntax.
← Python3 Pass StatementPython3 Func Hash β†’