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.
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¶
๐ 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: 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 โ