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.
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 β