Skip to content

Python If Else πŸš€ΒΆ

Prerequisites: Python Booleans

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¢

graph TD
    A[Start 🏁] --> B{Is it Raining? 🌧️}
    B -- Yes --> C[Take Umbrella β˜‚οΈ]
    B -- No --> D{Is it Sunny? β˜€οΈ}
    D -- Yes --> E[Wear Sunglasses 😎]
    D -- No --> F[Just Walk 🚢]
    C --> G[End 🏁]
    E --> G
    F --> G

πŸ’» Implementation: Decision LabΒΆ

# πŸ›’ 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 if block MUST be indented.
  • Short Hand (Ternary): For simple 1-line checks: result = "Pass" if score > 35 else "Fail"

🎯 Practice Lab πŸ§ͺΒΆ

Task: The ATM Withdrawal

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:. πŸ’‘


← Back: Booleans | Next: Loops β†’