Python Master Course V2 — 009. Conditional Statements and Professional Decision Flow
Module 01 · Python foundations · Lesson 009 / 200
Conditional Statements and Professional Decision Flow
Understand if, elif and else; write robust conditions, validate inputs, and build a practical decision-making application.
Level: Foundational with professional extensions | Learning time: 75–100 minutes | Practice: 45 minutes
In this lesson · 20 sections + self-check
- 🎬 Lesson video — reserved player slot
- Learning objectives and prerequisites
- 01. How an if statement changes execution
- 02. Two-way selection with else
- 03. Multi-way selection with elif
- 04. Independent if statements versus elif
- 05. Logical operators and grouping
- 06. Short-circuit evaluation
- 07. Truthiness and explicit comparisons
- 08. Normalize and validate text
- 09. Boundaries, ranges and state checks
- 10. Read user input safely
- 11. Clear guards and early returns
- 12. Professional mini-project: Scholarship Decision Engine
- 13. Test matrix and boundary analysis
- 14. Common mistakes and systematic debugging
- 15. Professional best practices
- 16. Guided practice, independent exercises and challenge
- 17. Knowledge check with answers
- 18. Summary and course navigation
- Interactive self-check
🎬 Lesson video — reserved player slot
Dedicated video for Lesson 009 will appear here after upload. No video has been embedded yet.
Video URL: Pending.
Learning objectives and prerequisites
Prerequisites: Lessons 001–008, especially comparison operators, Boolean values, strings and numeric types. Python 3.10+ is recommended.
- Trace one-way, two-way and multi-way execution paths.
- Distinguish mutually exclusive branches from independently applicable rules.
- Use compound conditions and short-circuit evaluation safely.
- Validate external data before making decisions.
- Design threshold tests, debug failed conditions and document assumptions.
- Build and test a scholarship eligibility console project.
01. How an if statement changes execution
Programs ordinarily execute from top to bottom. A conditional checks an expression for truthiness and executes its indented block only when the expression is true. The colon introduces the suite; use four spaces per indentation level.
Example 1 — one-way selection
temperature = 33
if temperature >= 30:
print("Hot weather: stay hydrated")
print("Forecast processed")Output: Hot weather: stay hydrated; Forecast processed. Change the value to 23 and observe that only the final statement prints.
02. Two-way selection with else
Use if/else when exactly one of two paths must execute. The else block needs no additional condition.
Example 2 — admission
age = 16
if age >= 18:
print("Adult admission")
else:
print("Junior admission")Output: Junior admission.
03. Multi-way selection with elif
Python evaluates an if/elif/else chain from top to bottom, then executes only the first matching branch. Place the most restrictive threshold first.
Example 3 — score bands
score = 84
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
elif score >= 60:
grade = "C"
else:
grade = "Needs improvement"
print(grade)Output: B. If score >= 60 came first, scores of 90+ would be incorrectly classified as C.
04. Independent if statements versus elif
When several actions may apply, use separate if statements. Do not use elif for conditions that must both be evaluated.
Example 4 — two valid benefits
cart_total = 2500
is_first_purchase = True
if cart_total >= 2000:
print("Free delivery")
if is_first_purchase:
print("Welcome gift")Output: Both messages print. A chained elif would incorrectly suppress one.
05. Logical operators and grouping
and requires both expressions, or requires at least one, and not negates a truth value. Use parentheses whenever a mixed expression might be misunderstood.
Example 5 — promotional policy
verified = True
total = 900
coupon = True
if verified and (total >= 1000 or coupon):
print("Promotion approved")
else:
print("Promotion rejected")Output: Promotion approved. Write the business rule in plain language before translating it into code.
06. Short-circuit evaluation
For and, Python skips the right expression when the left is false; for or, it skips the right when the left is true. Use this to avoid evaluating unsafe expressions.
Example 6 — empty-string guard
username = ""
if username and username[0].isalpha():
print("Valid initial")
else:
print("Enter a name starting with a letter")Output: Enter a name starting with a letter. An empty name never reaches username[0], avoiding IndexError.
07. Truthiness and explicit comparisons
Zero, empty strings and None are falsy. Nonempty strings such as "False" are truthy. This distinction makes bool(input()) unsuitable for parsing yes/no questions.
Example 7 — truthiness
print(bool(""))
print(bool("False"))
print(bool(0))
print(bool(1))Output: False, True, False, True (one line each). To check missing information without mistaking zero for absent, write value is None.
08. Normalize and validate text
External text may contain leading spaces or unexpected capitalization. Normalize it, then compare against a small set of supported values. Reject other inputs rather than guessing.
Example 8 — clear user intent
answer = " YES "
answer = answer.strip().casefold()
if answer in ("yes", "y"):
print("Confirmed")
elif answer in ("no", "n"):
print("Declined")
else:
print("Invalid choice")Output: Confirmed.
09. Boundaries, ranges and state checks
A chained comparison makes numeric validation readable. Use membership for permitted states, and test values just below, exactly at and just above thresholds.
Example 9 — range and status validation
attendance = 75
status = "active"
if 0 <= attendance <= 100 and status in {"active", "probation"}:
print("Valid record")
else:
print("Review input")Output: Valid record. Notice that 75 is included by <=.
10. Read user input safely
input() returns text. Convert numeric text and handle parsing errors separately from business-rule validation.
Example 10 — numeric parsing
raw = "19"
try:
age = int(raw)
except ValueError:
print("Whole number required")
else:
if 0 <= age <= 120:
print("Age accepted")
else:
print("Outside accepted range")Output: Age accepted. A string can be a valid integer but an invalid age (for example, -3).
11. Clear guards and early returns
For reusable functions, reject bad inputs early. This avoids deep nesting and keeps the successful logic readable. Functions receive fuller coverage in later lessons.
Example 11 — guard clause
def label_for(address):
if not address or not address.strip():
return "Address required"
return "Deliver to " + address.strip()
print(label_for(" Kurnool "))
print(label_for(""))Output: Deliver to Kurnool; Address required.
12. Professional mini-project: Scholarship Decision Engine
Scenario: A learner is eligible when marks ≥65, attendance ≥75%, and annual family income ≤₹200,000. Eligible learners with marks ≥90 and attendance ≥90% receive Merit; otherwise those with income ≤₹150,000 receive Need-based; all remaining eligible learners receive General. Merit has priority over Need-based. All values must first pass input validation.
Build steps: collect inputs → convert numbers → validate ranges → check disqualifying rules → select the first matching category → display an explainable outcome.
Complete runnable program — scholarship.py
from decimal import Decimal, InvalidOperation
print("SMARTYFY SCHOLARSHIP CHECKER")
name = input("Student name: ").strip()
raw_marks = input("Marks (0-100): ").strip()
raw_attendance = input("Attendance (0-100): ").strip()
raw_income = input("Annual family income INR: ").strip()
try:
marks = int(raw_marks)
attendance = Decimal(raw_attendance)
income = Decimal(raw_income)
except (ValueError, InvalidOperation):
print("Invalid numeric input")
raise SystemExit(1)
if not name:
print("Student name cannot be blank")
raise SystemExit(1)
valid = (
0 <= marks <= 100
and attendance.is_finite()
and 0 <= attendance <= 100
and income.is_finite()
and income >= 0
)
if not valid:
print("Input values out of accepted ranges")
raise SystemExit(1)
if marks < 65 or attendance < 75 or income > 200000:
decision = "NOT ELIGIBLE"
category = "NONE"
else:
decision = "ELIGIBLE"
if marks >= 90 and attendance >= 90:
category = "MERIT"
elif income <= 150000:
category = "NEED-BASED"
else:
category = "GENERAL"
print("Name:", name)
print("Decision:", decision)
print("Category:", category)
Example A: Anita, 92, 94, 185000 → ELIGIBLE / MERIT. Example B: Ravi, 75, 80, 120000 → ELIGIBLE / NEED-BASED. Example C: Leela, 60, 90, 100000 → NOT ELIGIBLE.
Professional note: Decimal avoids common binary floating-point representation issues for income and attendance. is_finite() rejects NaN and infinity values. A real service would also require authenticated records, an audit trail and privacy controls.
13. Test matrix and boundary analysis
| Marks | Attendance | Income | Expected result |
|---|---|---|---|
| 65 | 75 | 200000 | ELIGIBLE / GENERAL |
| 90 | 90 | 200000 | ELIGIBLE / MERIT |
| 85 | 82 | 150000 | ELIGIBLE / NEED-BASED |
| 64 | 100 | 0 | NOT ELIGIBLE |
| 100 | 74.99 | 0 | NOT ELIGIBLE |
| 100 | 100 | 200001 | NOT ELIGIBLE |
| 101 | 80 | 100000 | INVALID INPUT |
| 95 | NaN | 100000 | INVALID INPUT |
Boundary insight: Eligibility thresholds may be inclusive or exclusive. Verify the equality cases directly, rather than assuming they work.
14. Common mistakes and systematic debugging
- Missing colon:
if readymust beif ready:. - Indentation: statements inside a block must be consistently indented.
- Assignment/comparison: use
==to compare, not=. - Always-true or:
role == "admin" or "manager"is wrong; userole in ("admin", "manager"). - Unordered branches: broad conditions placed before specific ones hide later paths.
- Wrong branching pattern: use independent
ifs if two actions may both apply. - Unsafe inputs: never compare unconverted string inputs directly with numbers.
- Floating-point equality:
0.1 + 0.2 == 0.3is false in Python; choose an appropriate numeric strategy.
Debug process: reproduce → inspect values and types → describe the intended rule in plain English → trace each branch → fix the expression → rerun every boundary test.
15. Professional best practices
- Name Boolean variables positively and clearly:
is_active,has_permission. - Keep parsing, validation and business decisions conceptually separate.
- Document policy thresholds and test their boundary values.
- Prefer readable conditions with parentheses to clever one-liners.
- Use explicit
is Nonetests when zero is valid data. - Favor early rejection of invalid cases over deep nesting.
- Keep real applicants’ personal details out of debug logs.
- Refactor frequently used decisions into functions as projects expand.
16. Guided practice, independent exercises and challenge
Build age categories: negative = invalid, 0–17 = minor, 18–59 = adult, 60+ = senior.
Hint: age categories
Reject negative values first, then use an exclusive chain ordered by increasing thresholds.
Worked answer: age categories
def age_category(age): if age < 0: return "INVALID" elif age < 18: return "MINOR" elif age < 60: return "ADULT" else: return "SENIOR" for age in [-1, 0, 17, 18, 59, 60]: print(age, age_category(age))Expected output:
-1 INVALID 0 MINOR 17 MINOR 18 ADULT 59 ADULT 60 SENIORAfter a previous branch fails, its lower bound is already established. At age 18 the minor branch fails; at 60 the adult branch fails. Separate
ifblocks could classify the same value more than once.Free shipping applies when a customer is verified AND either the cart ≥₹1,000 OR a voucher exists. Code and test it.
Hint: verified free shipping
Keep verification outside the parentheses so neither cart value nor a voucher can bypass it.
Worked answer: verified free shipping
for verified, cart, voucher in [(False, 1200, True), (True, 999, False), (True, 1000, False), (True, 999, True)]: free_shipping = verified and (cart >= 1000 or voucher) print(verified, cart, voucher, free_shipping)Expected output:
False 1200 True False True 999 False False True 1000 False True True 999 True TrueVerification is required for both alternatives. The first case would expose a mistaken
verified and cart >= 1000 or voucherexpression. Exactly ₹1,000 qualifies because the comparison is inclusive.Make independent high-value and expedited-order notifications that can both print.
Hint: independent notifications
Both actions may apply, so use two independent if statements.
Worked answer: independent notifications
order_total = 60000 is_expedited = True if order_total > 50000: print("High-value order") if is_expedited: print("Expedited handling")Expected output:
High-value order Expedited handlingA chain with
elifwould skip the second notification after the first condition succeeds. Independent decisions should each be evaluated.Accept only yes/y or no/n regardless of surrounding spaces and capitalization.
Hint: yes/no parsing
Normalize once, match only the approved vocabulary, and reject every other value.
Worked answer: yes/no parsing
def parse_yes_no(text): value = text.strip().casefold() if value in {"yes", "y"}: return True if value in {"no", "n"}: return False raise ValueError("Enter yes/y or no/n.") for text in [" YES ", "n", "maybe"]: try: print(repr(text), parse_yes_no(text)) except ValueError as error: print(repr(text), error)Expected output:
' YES ' True 'n' False 'maybe' Enter yes/y or no/n.bool("no")would produce True because the string is nonempty. The parser deliberately distinguishes a valid False answer from invalid input.Test a 40-mark pass threshold with 39, 40, 41, -1 and 101.
Hint: pass threshold tests
Validate the score range before checking the passing minimum.
Worked answer: pass threshold tests
def result(score): if not 0 <= score <= 100: return "INVALID" elif score >= 40: return "PASS" else: return "FAIL" for score in [39, 40, 41, -1, 101]: print(score, result(score))Expected output:
39 FAIL 40 PASS 41 PASS -1 INVALID 101 INVALIDThe inclusive minimum admits 40. An impossible score of 101 must not be accepted simply because it exceeds 40.
Refactor the scholarship rules into a function that returns both decision and category.
Hint: scholarship function
Return a pair, preserve the original eligibility rules, and check Merit before Need-based.
Worked answer: scholarship function
This function accepts an integer mark and Decimal attendance and income, after the input conversions shown in the project.
from decimal import Decimal def scholarship(marks, attendance, income): if not (0 <= marks <= 100 and attendance.is_finite() and 0 <= attendance <= 100 and income.is_finite() and income >= 0): return "INVALID", "NONE" if marks < 65 or attendance < 75 or income > 200000: return "NOT ELIGIBLE", "NONE" if marks >= 90 and attendance >= 90: return "ELIGIBLE", "MERIT" if income <= 150000: return "ELIGIBLE", "NEED-BASED" return "ELIGIBLE", "GENERAL" for marks, attendance, income in [(92, "94", "185000"), (75, "80", "120000"), (60, "90", "100000"), (70, "80", "180000")]: decision, category = scholarship(marks, Decimal(attendance), Decimal(income)) print(decision, category)Expected output:
ELIGIBLE MERIT ELIGIBLE NEED-BASED NOT ELIGIBLE NONE ELIGIBLE GENERALReturning the decision and category separates policy from printing and makes repeatable tests possible. A candidate meeting both Merit and Need-based rules receives Merit because that branch is checked first.
Advanced challenge — Order Approval Engine
Positive order values are valid. Inactive accounts are blocked; fraud-flagged orders are held; unflagged orders over ₹50,000 require managerial review; the rest can be approved. Implement INVALID, BLOCKED, HELD, MANAGER_REVIEW, APPROVED statuses. Test values 0, 1, 50000 and 50001 and flagged/inactive combinations. Write a decision table and document precedence.
17. Knowledge check with answers
- When is
elifpreferable to anotherif? - After the first true
elifbranch, which subsequent branches run? - Is
bool("False")true or false? - Why does
role == "admin" or "manager"fail logically? - What are guard clauses and why do developers use them?
- What is the difference between
==andis? - What error might
int("two")raise? - Why test one below, at and one above a threshold?
Open answer key
1. For mutually exclusive decisions. 2. None. 3. True; it is a nonempty string. 4. A nonempty string makes the condition truthy; use membership or full comparisons. 5. Early validation/exit to avoid invalid processing and excess nesting. 6. Equality of values versus identity of objects. 7. ValueError. 8. To detect incorrect inclusive/exclusive comparisons.
18. Summary and course navigation
Conditional logic makes programs responsive and explainable. You can now implement if, elif, else, short-circuit expressions, input validation and testable business rules. Complete at least four independent exercises and explain each rule of the scholarship project before progressing.
Smartyfy Python Master Course V2 — Lesson 009 / 200
Apply what you learned
Interactive self-check
Choose an answer for each question, then check your work. You will see the correct answer and why it is correct.
This is a practice quiz. Results are saved on this browser when storage is available.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion and quiz results are stored on this browser.