Python If Else 🚀
Python If-Else Statements is a core Python concept covering learn how to make decisions in Python using If, Elif, and Else. Includes the Traffic Light scenario and flowcharts for logical branching. This topic is essential for academic learning, board exam preparation, and developing optimized real-world code.
Mentor's Note: Conditional logic is the "Brain" of your program. It allows your code to look at a situation and decide: "If this happens, do that!" 💡
🌟 The Scenario: The Traffic Light 🚦
Imagine you are driving your car towards an intersection.
- The Logic:
- IF the light is Green 🟢: GO!
- ELSE IF (Elif) the light is Yellow 🟡: SLOW DOWN!
- ELSE (If nothing else is true) 🔴: STOP!
- The Result: You navigate the intersection safely based on the current state. ✅
📖 Concept Explanation
1. The if Statement
The simplest form of decision making. If the condition is True, the code runs.
if score > 35:
print("You passed! 🎉")
2. The elif (Else If)
Used when you have more than two options to check. You can have as many elif blocks as you need.
3. The else
The "Catch-All". It runs if NONE of the previous conditions were true.
🎨 Visual Logic: The Decision Flow
💻 Implementation: Decision Lab
- Python (3.10+)
# 🛒 Scenario: Grading a Student
# 🚀 Action: Using if-elif-else ladder
score = 85
if score >= 90:
grade = "A+ 🏆"
elif score >= 80:
grade = "A ✨"
elif score >= 70:
grade = "B 👍"
else:
grade = "Keep trying! 💪"
print(f"Your result: {grade}")
# 🛍️ Outcome: "Your result: A ✨"
📊 Sample Dry Run (Ladder)
Input: score = 75
| Step | Condition | Result | Action |
|---|---|---|---|
| 1 | score >= 90 | False | Skip to next ⏭️ |
| 2 | score >= 80 | False | Skip to next ⏭️ |
| 3 | score >= 70 | True ✅ | Assign "B" and EXIT ladder! |
📈 Technical Analysis
- Indentation: Every line inside an
ifblock MUST be indented. - Short Hand (Ternary): For simple 1-line checks:
result = "Pass" if score > 35 else "Fail"
🎯 Practice Lab 🧪
Task: Write a program where balance = 500. Ask for a withdrawal amount. If withdrawal <= balance, print "Success", else print "Insufficient Funds".
Hint: Use if withdrawal <= balance:. 💡
🔗 Related Topics
← Back: Booleans | Next: Loops →