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.
- 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
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)- 1.Line 5: 75 > 70 evaluates to True.
- 2.Line 8: 75 != 50 evaluates to True.
- 3.Line 12: quarantine_reason is None checks if the variable points to the NoneType singleton -> True.
- 4.Line 16: Evaluates (18 <= 25) and (25 < 65) simultaneously -> True.
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
• 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
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)- 1.Line 6: (True and True) evaluates to True. not False is True. True and True evaluates to True.
- 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.Line 12: Outputs False safely without raising a ZeroDivisionError.
Should quarantine : True Safe division ran without crash: False
• '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)
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)")- 1.Line 6: user_input is '', which is falsy. not '' evaluates to True.
- 2.Line 9: suspicious_count is 0, which is falsy. not 0 evaluates to True.
- 3.Line 12: sender_domain is 'corp.org', which has length > 0, so it is truthy.
1. user_input is empty (falsy) 2. suspicious_count is zero (falsy) 3. sender_domain is present (truthy)
• 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
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)- 1.Line 3: 68 >= 80 is False -> passes to line 6.
- 2.Line 6: 68 >= 60 is True -> executes lines 7 and 8.
- 3.Lines 9-14: Skipped entirely due to mutual exclusivity.
- 4.Lines 15-17: Outputs the determined verdict and action.
Risk Score : 68 Verdict : SUSPICIOUS Action : Move to Junk & Append Warning Tag
• 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
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)- 1.Line 5: Evaluates risk_score > 70 (True), assigning 'AGGRESSIVE'.
- 2.Line 9: Outer condition risk_score > 70 is True -> enters inner block.
- 3.Line 10: user_tier == 'VIP' is True -> assigns 'Escalate to Human Analyst'.
- 4.Line 16: Outputs final routing decision.
Filter Mode : AGGRESSIVE Disposition : Escalate to Human Analyst
• 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
basicModify 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.
Automated Financial Loan & Risk Underwriting Engine
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.
- 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.
- 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.
# 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
Chapter summary
Key concepts and syntax cards for review
- 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.
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?