Python Master Course V2 — 018. Nested Conditions and Decision Trees
SMARTYFY · PYTHON MASTER COURSE V2 · MODULE 02 · LESSON 018/200
Nested Conditions and Decision Trees
Estimated study: 60–90 minutes. Prerequisite: Lesson 017
nested decisions, early returns and policy rules.
Video lesson
Video not yet available.
Learning objectives
Explain nested decisions, early returns and policy rules, trace control flow, identify boundary cases, debug errors and implement a real-world decision-making project.
Prerequisites: Python 3.10+, variables, types, comparison expressions, and prior course lessons.
Understand and apply: Nested Conditions and Decision Trees
A decision tree records which questions matter next
Nested conditions express a dependency between decisions. An inner if is evaluated only after execution enters its enclosing suite. This is useful when the next question depends on the previous answer, such as choosing a return window after learning whether an item is damaged. Think of each condition as a fork in a path; a return at the end of a path selects the outcome and stops the function call.
Begin with a written policy rather than adding branches until samples pass. For this classroom refund policy, days must be a nonnegative integer and both receipt and damaged must be Booleans. Invalid data is rejected first. A missing receipt returns Receipt required regardless of damage. With a receipt, damaged items are approved through day 30; undamaged items are approved through day 14. Later requests go to Review. These rules are invented teaching rules, not a statement of any seller's actual refund terms.
Trace the paths that share the same inputs
Nested policy with explicit guards
def refund(days, receipt, damaged):
if type(days) is not int or type(receipt) is not bool or type(damaged) is not bool:
return "Invalid"
if days < 0:
return "Invalid"
if not receipt:
return "Receipt required"
if damaged:
if days <= 30:
return "Approve"
return "Review"
if days <= 14:
return "Approve"
return "Review"
print(refund(30, True, True))
print(refund(31, True, True))
print(refund(15, True, False))
print(refund(2, False, True))
Expected output:
Approve
Review
Review
Receipt required
For the first call, the type and range guards pass, the receipt exists, and damaged is True. The inner condition includes day 30, so the function returns Approve. Day 31 follows the same path until the window check fails, then returns Review. The undamaged day-15 request never enters the damaged suite and exceeds its own 14-day window. The missing-receipt request returns before damage or window eligibility can affect the outcome.
Flatten a tree without changing its meaning
Early returns remove paths that need no further work. Once invalid input and missing receipt are handled, the remaining task is only to choose the correct window and compare days with it. The equivalent core below can replace the damaged/undamaged part after the same guards. A conditional expression is introduced formally in the next lesson, so this version deliberately uses an ordinary if/else.
Equivalent window selection after the guards
days = 30
receipt = True
damaged = True
# Here the inputs are already valid and receipt is present.
if damaged:
limit = 30
else:
limit = 14
if days <= limit:
print("Approve")
else:
print("Review")
Expected output:
Approve
Flattening is successful only if every input keeps its previous outcome. Check 14/15 for undamaged items, 30/31 for damaged items, missing receipts in both groups, and negative days. A test on the ordinary day-5 case alone cannot establish equivalence. Also preserve precedence: moving the receipt guard below an approval return would allow some missing-receipt requests through.
Nesting is not inherently wrong; it is helpful when the indentation makes dependencies visible. Excessive nesting makes readers remember too many unfinished paths. Use early returns for clear stop conditions, then keep the main decision shallow. Avoid combining branches merely to reduce line count if the result obscures which rule won. A useful debugging explanation names the exact path and first returning rule, rather than saying the program chose the correct answer.
Runnable examples
Save each example in a separate lesson_018.py file and run with python lesson_018.py. These are expected outputs, not claims of execution in the browser.
Example 1: Nested
logged_in=True
verified=True
if logged_in:
if verified:
print("Access granted")
Expected output:
Access granted
Example 2: Early return
def permit(active,trained):
if not active:
return "Inactive"
if not trained:
return "Training required"
return "Allowed"
print(permit(True,False))
Expected output:
Training required
Guided project: Refund-window decision tree
This practical exercise turns a small set of business rules into predictable results. Read each branch, predict the result, then run the test cases. Modify one rule and add tests for its boundaries.
def refund(days,receipt,damaged):
if type(days) is not int or type(receipt) is not bool or type(damaged) is not bool:
return "Invalid"
if days<0:
return "Invalid"
if not receipt:
return "Receipt required"
if damaged:
if days<=30:
return "Approve"
return "Review"
if days<=14:
return "Approve"
return "Review"
for case in [(5,True,False),(20,True,False),(20,True,True),(2,False,True)]:
print(refund(*case))
Testing: Check ordinary accepted cases, rejected cases, exact thresholds, and malformed inputs. The sample focuses on the lesson’s branching concepts; a production system must additionally validate external inputs and enforce permissions server-side.
Common mistakes and best practices
- Failing to check invalid values before decision logic.
- Misunderstanding branch ordering and short-circuit behavior.
- Using overly complex nested expressions instead of readable predicates.
- Not testing equality at inclusive thresholds.
- Confusing illustrative classroom policies with real-world requirements.
Practice and reason it through
Attempt each question before opening its answer. Write down the result and the reason, then compare your reasoning with the worked solution.
1. What happens at the damaged-item boundary?
Reveal answer and explanation
With a receipt and damaged=True, day 30 is Approve because the check uses <= 30. Day 31 is Review. The undamaged 14-day limit is irrelevant after execution has selected the damaged path.
2. Which condition wins for a missing receipt?
Reveal answer and explanation
refund(2, False, True) returns Receipt required. The guard exits the function before the damaged-item window is considered. A short duration does not override the receipt rule under the stated policy.
3. Repair a refactor that approves before checking the receipt.
Reveal answer and explanation
Keep the receipt guard before all approval returns. Otherwise a damaged day-5 item can be approved even with no receipt. The order of early returns is part of the policy, not just a stylistic choice.
def damaged_refund(days, receipt):
if not receipt:
return "Receipt required"
if days <= 30:
return "Approve"
return "Review"
# Inputs for this small helper are already validated.
print(damaged_refund(5, False))
Expected output:
Receipt required
4. Which four valid boundary cases distinguish the two windows?
Reveal answer and explanation
Use receipt=True with (days=14, damaged=False) → Approve, (15, False) → Review, (30, True) → Approve, and (31, True) → Review. They exercise both inclusive endpoints and the first rejected day of each window. Add invalid and missing-receipt cases separately.
5. When are a nested version and a flat version equivalent?
Reveal answer and explanation
They must return the same result for every permitted input, reject the same invalid inputs, and preserve any relevant side effects. Choosing a limit of 30 for damaged items and 14 otherwise is equivalent only after the same validation and receipt checks. Compare the exact boundary and precedence cases, not just one successful return.
Further challenge
- Challenge: extend the project with a new policy and document three tests including one boundary case.
Mastery checkpoint
Demonstrate that you can predict the examples, explain branch order, run the project, and write at least three additional tests. Summary: nested decisions, early returns and policy rules require explicit reasoning, validation, and reproducible testing.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.