Ch 04Conditional Logic and Decision Making
Chapter 04 of 08·20 min

Conditional Logic and Decision Making

Intelligent computer systems must make decisions: should this transaction be flagged as fraud? Does an email contain phishing characteristics? Should a self-driving vehicle apply the brakes? In this chapter, you will master Python's conditional logic: boolean truth values, comparison and identity operators, logical operators with short-circuit evaluation, the if-elif-else decision tree, and clean Pythonic guard clauses.

Learning objectives
  • 01Construct boolean expressions using comparison operators (==, !=, <, <=, >, >=) and understand identity (is vs ==)
  • 02Combine complex conditions using logical operators (and, or, not) adhering to strict operator precedence
  • 03Evaluate truthiness and falsiness across Python types and avoid common truth-value traps
  • 04Architect structured decision trees using if, elif, and else statements with mandatory 4-space indentation
  • 05Implement concise inline conditional assignments using ternary expressions (a if cond else b)
  • 06Diagnose and avoid critical edge cases: short-circuit return values, chained comparison evaluation, and float comparison inaccuracies

4.1 Comparison Operators & Value Equality vs Identity

At the core of branching logic is the **comparison operator**, which evaluates two expressions and returns a boolean `True` or `False`. ### Comparison Operators: | Operator | Meaning | Example | Result | | :--- | :--- | :--- | :--- | | `==` | Value Equality | `10 == 10` | `True` | | `!=` | Not Equal | `10 != 5` | `True` | | `<` | Less Than | `5 < 10` | `True` | | `<=` | Less Than or Equal | `10 <= 10` | `True` | | `>` | Greater Than | `15 > 20` | `False` | | `>=` | Greater Than or Equal | `20 >= 18` | `True` | ### Equality (`==`) vs Identity (`is`): - `==` checks **value equality**: Do the two objects contain the same data? - `is` checks **object identity**: Do the two variables point to the **exact same memory address**? *Rule of thumb: Always use `==` for comparing numbers and strings; always use `is` when comparing against `None` (`if val is None:`).*
Statement 1: Equality, Comparisons & Identity Checks

Evaluating value equality, inequalities, and None identity checks.

threat_score = 75
THRESHOLD = 70

# Standard numeric comparisons
print("Score exceeds threshold (>)  :", threat_score > THRESHOLD)
print("Score at least threshold (>=) :", threat_score >= THRESHOLD)
print("Exact match (==)              :", threat_score == 75)
print("Mismatch (!=)                 :", threat_score != 50)

# Identity check for None
quarantine_reason = None
print("Reason is None (is)           :", quarantine_reason is None)

# Chained comparison (Idiomatic Python!)
age = 25
print("Age in range (18 <= age < 65) :", 18 <= age < 65)
Execution walkthrough
  1. 1.Line 5: 75 > 70 evaluates to True.
  2. 2.Line 8: 75 != 50 evaluates to True.
  3. 3.Line 12: quarantine_reason is None checks if the variable points to the NoneType singleton -> True.
  4. 4.Line 16: Evaluates (18 <= 25) and (25 < 65) simultaneously -> True.
Expected output
Score exceeds threshold (>)  : True
Score at least threshold (>=) : True
Exact match (==)              : True
Mismatch (!=)                 : True
Reason is None (is)           : True
Age in range (18 <= age < 65) : True
Edge cases

• Single '=' vs Double '==': Writing `if score = 75:` raises a `SyntaxError: invalid syntax. Maybe you meant '==' or ':='?`. Python prevents the classic C bug where accidental assignment evaluates as true. • Float comparisons: Never write `0.1 + 0.2 == 0.3` because it evaluates to `False` due to binary floating-point representation! Instead write: `abs((0.1 + 0.2) - 0.3) < 1e-9` or `math.isclose()`.

Why it happens: Python translates chained comparisons into short-circuited conjunctions.

4.2 Logical Operators & Short-Circuit Evaluation

Complex decisions require combining multiple conditions using **logical operators**: - **`and`**: Returns True only if **both** operands are truthy. - **`or`**: Returns True if **at least one** operand is truthy. - **`not`**: Unary operator that inverts the boolean state (`not True` -> `False`). ### Operator Precedence: 1. Comparison operators (`==`, `<`, etc.) 2. `not` 3. `and` 4. `or` ### The Mechanics of Short-Circuit Evaluation: Python uses lazy evaluation: - In `A and B`: If `A` is False, Python **never evaluates `B`** (because the outcome is guaranteed to be False). - In `A or B`: If `A` is True, Python **never evaluates `B`** (because the outcome is guaranteed to be True). This is crucial for preventing runtime crashes (e.g. checking length before indexing).
Statement 2: Logical Operators and Short-Circuit Protection

Combining criteria and using short-circuiting to prevent ZeroDivisionError.

has_attachment = True
risk_rating = 85
is_whitelisted = False

# Combining conditions with 'and', 'or', 'not'
should_quarantine = (has_attachment and risk_rating > 80) and not is_whitelisted
print("Should quarantine :", should_quarantine)

# Short-circuit division protection
total_samples = 0
# Notice: If total_samples > 0 is False, the second division NEVER executes!
safe_division = total_samples > 0 and (100 / total_samples > 5)
print("Safe division ran without crash:", safe_division)
Execution walkthrough
  1. 1.Line 6: (True and True) evaluates to True. not False is True. True and True evaluates to True.
  2. 2.Line 11: total_samples is 0. 0 > 0 evaluates to False. Because the operator is 'and', the second operand (100 / 0) is discarded.
  3. 3.Line 12: Outputs False safely without raising a ZeroDivisionError.
Expected output
Should quarantine : True
Safe division ran without crash: False
Edge cases

• 'and' and 'or' Return the Actual Operand: In Python, `x or y` does not strictly return a boolean! It returns the first truthy operand, or the last operand if all are falsy. E.g.: `'' or 'default_user'` returns `'default_user'`! `0 or 42` returns `42`. • Operator Precedence Ambiguity: `False and False or True` evaluates to `True` because `and` binds before `or`! Always use explicit parentheses `()` for clarity in production code.

Why it happens: Python evaluates boolean expressions from left to right and stops evaluating as soon as the final outcome is mathematically determined (short-circuiting).

4.3 Truth Value Testing (Truthiness & Falsiness)

In Python, **any object can be tested for truth value** inside an `if` statement. ### The Falsy Values in Python: Every object in Python is considered **Truthy** EXCEPT the following, which evaluate to **False**: - Constants: `None`, `False` - Numeric zeros: `0`, `0.0`, `0j` - Empty sequences and collections: `""` (empty str), `[]` (empty list), `()` (empty tuple), `{}` (empty dict), `set()` ### The Idiomatic Python Style (PEP 8): Instead of writing `if len(email_text) > 0:`, write `if email_text:`. If the string is non-empty, it is truthy; if empty, it is falsy.
Statement 3: Truthy & Falsy Value Testing

Testing presence of strings, numbers, and collections without explicit length checks.

user_input = ""       # Empty string (falsy)
suspicious_count = 0  # Zero (falsy)
sender_domain = "corp.org" # Non-empty (truthy)

# Idiomatic truthiness testing
if not user_input:
    print("1. user_input is empty (falsy)")

if not suspicious_count:
    print("2. suspicious_count is zero (falsy)")

if sender_domain:
    print("3. sender_domain is present (truthy)")
Execution walkthrough
  1. 1.Line 6: user_input is '', which is falsy. not '' evaluates to True.
  2. 2.Line 9: suspicious_count is 0, which is falsy. not 0 evaluates to True.
  3. 3.Line 12: sender_domain is 'corp.org', which has length > 0, so it is truthy.
Expected output
1. user_input is empty (falsy)
2. suspicious_count is zero (falsy)
3. sender_domain is present (truthy)
Edge cases

• Testing 'if x is not None:' vs 'if x:': If x = 0, 'if x:' is False because 0 is falsy! If 0 is a valid numerical score you want to process, you must explicitly test: `if score is not None:`. • The string '0': A string containing '0' (`'0'`) has length 1 and is TRUTHY! Only the empty string `''` is falsy.

Why it happens: Python calls an object's internal __bool__() or __len__() method to resolve truthiness.

4.4 The if, elif, and else Decision Ladder

The `if-elif-else` statement is Python's mechanism for multi-branch decision making. ### Execution Flow: 1. Python checks the first `if condition:`. 2. If True, it executes that block and **skips all remaining elif and else blocks**. 3. If False, it proceeds down to the next `elif condition:` in sequential order. 4. If none of the conditions evaluate to True, the final `else:` block executes as a fallback. ### Indentation Syntax: Python does not use `{}` braces. Every code block is defined strictly by **4 spaces of indentation**. Consistent indentation is strictly enforced by the Python interpreter.
Statement 4: Multi-Branch Classification with if-elif-else

Classifying threat levels based on continuous risk scores.

risk_score = 68

if risk_score >= 80:
    verdict = "CRITICAL THREAT"
    action = "Immediate Quarantine & Admin Alert"
elif risk_score >= 60:
    verdict = "SUSPICIOUS"
    action = "Move to Junk & Append Warning Tag"
elif risk_score >= 30:
    verdict = "LOW RISK"
    action = "Deliver with Standard Filter"
else:
    verdict = "CLEAN"
    action = "Direct Inbox Delivery"

print("Risk Score :", risk_score)
print("Verdict    :", verdict)
print("Action     :", action)
Execution walkthrough
  1. 1.Line 3: 68 >= 80 is False -> passes to line 6.
  2. 2.Line 6: 68 >= 60 is True -> executes lines 7 and 8.
  3. 3.Lines 9-14: Skipped entirely due to mutual exclusivity.
  4. 4.Lines 15-17: Outputs the determined verdict and action.
Expected output
Risk Score : 68
Verdict    : SUSPICIOUS
Action     : Move to Junk & Append Warning Tag
Edge cases

• Ordering conditions incorrectly: If you test `elif risk_score >= 30:` before `elif risk_score >= 80:`, a score of 95 would trigger the >= 30 branch and stop! Always order continuous threshold ladders from most restrictive to least restrictive (or vice versa). • Using consecutive 'if' statements: Replacing 'elif' with 'if' means every condition is tested independently, which can overwrite variables multiple times.

Why it happens: The elif ladder guarantees mutual exclusivity: exactly one block executes.

4.5 Nested Conditionals & Ternary Expressions

When decisions depend on hierarchical sub-conditions, conditional statements can be nested. In addition, Python provides a compact **Ternary Operator (Conditional Expression)** for assigning values in a single line: `variable = value_if_true if condition else value_if_false` This is widely used in data transformation and feature engineering.
Statement 5: Ternary Expression & Nested Validation

One-line conditional assignment and hierarchical logic.

risk_score = 75
user_tier = "VIP"

# One-line ternary conditional expression
filter_mode = "AGGRESSIVE" if risk_score > 70 else "STANDARD"
print("Filter Mode :", filter_mode)

# Nested condition logic
if risk_score > 70:
    if user_tier == "VIP":
        disposition = "Escalate to Human Analyst"
    else:
        disposition = "Automated Quarantine"
else:
    disposition = "Normal Delivery"

print("Disposition :", disposition)
Execution walkthrough
  1. 1.Line 5: Evaluates risk_score > 70 (True), assigning 'AGGRESSIVE'.
  2. 2.Line 9: Outer condition risk_score > 70 is True -> enters inner block.
  3. 3.Line 10: user_tier == 'VIP' is True -> assigns 'Escalate to Human Analyst'.
  4. 4.Line 16: Outputs final routing decision.
Expected output
Filter Mode : AGGRESSIVE
Disposition : Escalate to Human Analyst
Edge cases

• Deep nesting anti-pattern: Nesting conditionals more than 3 levels deep creates the 'arrow anti-pattern' which makes code unreadable. Refactor deep nesting using early return statements or combined boolean logic.

Why it happens: Ternary expressions return values directly and can be used inside print() calls or function arguments.

Practice exercise

Work through the exercise before starting the chapter assignment

Exercise 4: Security Threat Level Classifier

basic

Modify the starter code to assign 'HIGH' if threat_count >= 3, 'MEDIUM' if threat_count is 1 or 2, and 'SAFE' if threat_count is 0. Print the assigned status.

Chapter 04 assignmentMilestone

Automated Financial Loan & Risk Underwriting Engine

Scenario

A fintech digital banking platform at the Center of Excellence requires an automated credit evaluation module. The engine must ingest an applicant's credit score, annual salary, debt-to-income (DTI) percentage, and previous bankruptcy count, evaluate multi-tier underwriting policies, apply automatic disqualifiers, and generate a final credit verdict.

Implementation requirements
  • Define applicant metrics: credit_score = 710, annual_salary = 65000, dti_ratio = 32.5, bankruptcies = 0.
  • Disqualification Rule: If bankruptcies > 0, verdict must immediately be 'REJECTED: ADVERSE BANKRUPTCY RECORD' regardless of credit score.
  • Multi-tier Approval Rules (when bankruptcies == 0):
  • - Prime Approval: credit_score >= 750 AND dti_ratio <= 35.0 -> 'APPROVED: PRIME TIER'
  • - Standard Approval: credit_score >= 680 AND dti_ratio <= 40.0 AND annual_salary >= 45000 -> 'APPROVED: STANDARD TIER'
  • - Conditional Approval: credit_score >= 620 AND annual_salary >= 60000 -> 'APPROVED: CONDITIONAL REVIEW'
  • - Rejection: Otherwise -> 'REJECTED: RISK PROFILE EXCEEDED'
  • Use a ternary expression to compute interest_rate: 4.5 if verdict starts with 'APPROVED: PRIME' else 6.8.
  • Print a formatted Underwriting Summary displaying credit score, DTI, decision verdict, and interest rate.
Edge cases to handle
  • 1.Bankruptcy short-circuit: The bankruptcy disqualifier must be tested first before numerical threshold ladders.
  • 2.Boundary condition: credit_score exactly 680 and DTI exactly 40.0 must qualify for standard approval (use >= and <=).
  • 3.Ensure float percentages are evaluated accurately.
Starter template
# Chapter 4 Assignment: Automated Financial Risk Underwriting Engine
# Center of Excellence: Data Science & AI

applicant_name = "Marcus Vance"
credit_score = 710
annual_salary = 65000
dti_ratio = 32.5
bankruptcies = 0

# TODO: Step 1 - Check if bankruptcies > 0 (Immediate Rejection)
# TODO: Step 2 - Evaluate Prime, Standard, Conditional, or Rejection
# TODO: Step 3 - Assign interest_rate using ternary operator
# TODO: Step 4 - Print Underwriting Decision Summary
Progressive hints

Chapter summary

Key concepts and syntax cards for review

Key concepts
  • 01Comparison operators (==, !=, <, <=, >, >=) evaluate expressions to boolean True or False.
  • 02== checks value equality; 'is' checks object identity (same memory address). Always use 'is None'.
  • 03Logical operators follow precedence: not > and > or. Use parentheses to enforce explicit evaluation order.
  • 04Short-circuit evaluation stops evaluating logical operands as soon as the outcome is guaranteed.
  • 05The if-elif-else ladder executes only the first matching branch in top-to-bottom sequence.
Syntax reference
if condition: ... elif other: ... else: ...Multi-branch decision control structure.
cond_a and cond_b / cond_a or cond_bLogical conjunction and disjunction with short-circuit evaluation.
val = true_val if condition else false_valTernary conditional expression for inline assignments.

Knowledge check

Verify your grasp of the chapter concepts

What will be printed by: print('A' if 0 else 'B')?

What does Python do when evaluating: False and (10 / 0 == 1)?

Which of the following is TRUTHY in Python?