Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
if, elif, else & Indentation ArchitecturePrograms do not simply run in a straight linear sequence from line 1 to line 100. Real-world applications make decisions: if an ATM withdrawal amount exceeds the account balance, reject the transaction; if a user enters valid credentials, grant dashboard access; otherwise, prompt for multi-factor authentication.
In Python, decision-making is implemented through conditional statements: if, elif (short for else if), and else. Instead of using curly braces {} or keywords like then/endif, Python uses indentation (4 spaces) to define code blocks, producing clean and human-readable branching logic.
+-------------------------------------------------------------------------+
| CONTROL FLOW REAL-WORLD ANALOGY |
+-------------------------------------------------------------------------+
1. THE RAILWAY SHUNTING SWITCH (Mughalsarai / DDU Junction):
- An express train approaches a multi-track railway junction.
- Track switch lever checks condition:
* If Platform 1 is clear? -> Divert train to Platform 1.
* Elif Platform 2 is clear? -> Divert train to Platform 2.
* Else -> Divert train to holding siding loop.
- Crucial Rule: The train can only take ONE track! Once Platform 1
lever engages, all other levers are ignored.
2. THE TRAFFIC SIGNAL CONTROLLER:
- Traffic light color checks:
* If light is "RED" -> Apply emergency brakes.
* Elif light is "AMBER" -> Decelerate and prepare to stop.
* Else (GREEN) -> Accelerate safely through junction.
+-------------------------------------------------------------------------+if Statement & Python IndentationIn Python, an if statement evaluates an expression. If the expression evaluates to True, the indented block underneath executes:
if-elseWhen an action must be taken both when the condition is met and when it fails, pair if with else:
if-elif-else LadderWhen classifying data across multiple thresholds, use elif. Python tests conditions from top to bottom and executes only the first branch whose condition evaluates to True (short-circuit branching):
Python does not require explicit comparison operators (== True). Any object can be evaluated directly for its inherent truthiness:
| Scenario | ❌ Anti-Pattern | ✅ Pythonic Idiom |
|---|---|---|
| Boolean Comparison | if is_admin == True: | if is_admin: |
| Empty Check | if len(items) > 0: | if items: |
| Check for None | if result == None: | if result is None: |
| Order in elif | Broad conditions before specific conditions | Specific conditions before broad conditions |
| Mixed Indentation | Mixing Tab characters with spaces | Strictly use 4 spaces per indentation level |
+---------------------------------------------------------------------------+
| PYTHON IF-ELIF-ELSE CHEAT SHEET |
+---------------------------------------------------------------------------+
| Statement | Meaning / Behavior |
|----------------------+----------------------------------------------------|
| if condition: | Executes indented block if condition is True |
| elif condition: | Evaluated ONLY if preceding if/elif were False |
| else: | Fallback block if ALL preceding tests were False |
| Indentation Rule | Standard 4 spaces; defines code block boundaries |
| First-Match Wins | Once any branch executes, remaining elifs skipped |
| Falsy Values | False, None, 0, 0.0, "", [], (), {}, set() |
+---------------------------------------------------------------------------+Python requires consistent indentation (recommended: 4 spaces). Mixing tabs and spaces raises an IndentationError:
:)Every if, elif, and else statement must end with a colon:
A. Curly braces {} B. Semicolons ; C. Consistent indentation (typically 4 spaces) D. then and endif keywords
A. Banana and Cherry B. Banana C. Cherry D. Date
A. [] (empty list) B. 0 (integer zero) C. "0" (string containing digit zero) D. None
if-elif chain are met and there is NO else clause?A. Python raises a RuntimeError B. Python throws a SyntaxError C. Nothing inside the conditional executes; program continues past it D. Python executes the first elif block by default
items is not empty?A. if len(items) != 0: B. if items == True: C. if items: D. if bool(items) == True:
Design an automated ticket fare calculation engine for an Indian Railways journey. The base fare from New Delhi to Varanasi in 3AC is Rs 1,150. Implement age and status concession logic: children under 5 travel free (100% discount), senior citizens aged 60+ receive a 40% senior concession, bonafide students with valid ID receive a 25% discount, and passengers with medical disability concessions receive 50% off. Apply the highest single eligible concession.
In the next lesson, we will continue your Python learning journey with Nested Conditions (12: Conditional Statements).
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Project: Student Records | Nested Conditions |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.