10.Python’s if, elif, and else statements
Python’s if, elif, and else statements control the flow of your program by executing different blocks of code based on conditions. They allow your code to “make decisions” and respond dynamically.
Here’s a detailed breakdown of how each part works:
🧠 The Basics of Control Flow
- Control flow refers to the order in which your code executes.
- Python uses conditional statements to decide which block of code runs based on whether a condition is True or False.
✅ if Statement
- The if statement checks a condition.
- If the condition is True, the indented block below it runs.
x = 10 if x > 5: print(“x is greater than 5”)
Only runs if x > 5 is true.
🔄 elif (Else If)
- Used to check additional conditions if the first if is False.
- You can have multiple elif blocks.
x = 0 if x < 0: print(“Negative”) elif x == 0: print(“Zero”) elif x == 1: print(“One”)
Each condition is checked in order. The first one that’s True runs, and the rest are skipped.
🧯 else Statement
- Acts as a fallback when none of the if or elif conditions are met.
- No condition needed — it always runs if reached.
x = 5 if x < 0: print(“Negative”) elif x == 0: print(“Zero”) else: print(“Positive number”)
🧩 Flowchart Summary
- Python checks the if condition.
- If True, executes that block and skips the rest.
- If False, checks each elif in order.
- If none match, executes the else block (if present).
🔍 Real-Life Example: Grading System
score = 85 if score >= 90: grade = ‘A’ elif score >= 80: grade = ‘B’ elif score >= 70: grade = ‘C’ else: grade = ‘F’ print(“Your grade is:”, grade)
This structure helps categorize values into ranges.
🧠 Tips for Clean Control Flow
- Use logical operators (and, or, not) to combine conditions.
- Avoid deeply nested if blocks — use elif to keep code readable.
- Use boolean expressions directly (e.g., if is_active: instead of if is_active == True:).