Skip to content

Python If Else ๐Ÿš€

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 โ†’