Case Study: How Conditional Logic Powers Everyday Technology
Overview
Every time you withdraw cash from an ATM, drive through a traffic light, or see a movie recommendation on a streaming service, conditional logic is making decisions behind the scenes. This case study examines three real-world systems and traces their decision-making back to the same if-elif-else patterns you learned in Chapter 4.
The goal isn't to show you the actual source code of these systems — that's proprietary and far more complex than what we've covered. The goal is to demonstrate that the thinking is the same. The scale changes. The syntax might differ. But the fundamental structure — evaluate a condition, choose a path — is universal.
System 1: The Automated Teller Machine (ATM)
What You See
You walk up to an ATM, insert your card, enter your PIN, and request $200. A few seconds later, cash comes out. Simple.
What's Happening
Behind that simple interaction is a cascade of conditional logic. Here's a simplified model of the withdrawal decision:
"""
Simplified ATM withdrawal logic.
Real ATMs have far more checks, but the structure is the same.
"""
# --- Simulated data ---
card_valid = True
pin_entered = "4729"
correct_pin = "4729"
account_balance = 1543.67
daily_withdrawal_limit = 500.00
machine_cash_available = 8000.00
withdrawal_amount = 200.00
# --- Authentication ---
if not card_valid:
print("Card not recognized. Please contact your bank.")
elif pin_entered != correct_pin:
print("Incorrect PIN. Please try again.")
# Real ATMs track failed attempts and lock after 3
# --- Withdrawal validation ---
elif withdrawal_amount <= 0:
print("Invalid amount. Please enter a positive value.")
elif withdrawal_amount % 20 != 0:
print("Please enter an amount in multiples of $20.")
elif withdrawal_amount > daily_withdrawal_limit:
print(f"Amount exceeds daily limit of ${daily_withdrawal_limit:.2f}.")
elif withdrawal_amount > account_balance:
print("Insufficient funds.")
print(f"Available balance: ${account_balance:.2f}")
elif withdrawal_amount > machine_cash_available:
print("This ATM cannot dispense that amount right now.")
print("Please try a smaller amount or use another machine.")
# --- All checks passed ---
else:
account_balance -= withdrawal_amount
machine_cash_available -= withdrawal_amount
print(f"Dispensing ${withdrawal_amount:.2f}")
print(f"New balance: ${account_balance:.2f}")
print("Don't forget to take your card!")
Expected output (with default values):
Dispensing $200.00
New balance: $1343.67
Don't forget to take your card!
The Key Insight
Notice the structure: a long if-elif-else chain where each condition is a validation gate. The withdrawal only succeeds if it passes every single check. This is the same pattern Elena uses in TaskFlow v0.3 — validate input at each stage, and only proceed when everything is valid.
In a real ATM, there are additional checks we've omitted: network connectivity, fraud detection algorithms, denomination availability (does the machine have enough $20 bills?), transaction logging, receipt printing, and timeout handling. But every one of those checks is a conditional — an if that decides whether to proceed or abort.
What Would Happen Without Conditionals
Without these checks, the ATM would blindly dispense cash regardless of balance, PIN, or card validity. The conditions are what make the system safe. This is a pattern you'll see throughout your career: conditionals are the guardians that enforce business rules and prevent invalid operations.
System 2: The Traffic Light Controller
What You See
You approach an intersection. The light is green. It turns yellow. Then red. Cross traffic gets a green. Pedestrians get a walk signal. The cycle repeats.
What's Happening
A traffic light controller is a state machine — it tracks the current state of the intersection and uses conditionals to determine the next state. Here's a simplified model:
"""
Simplified traffic light controller logic.
Real controllers use hardware timers and sensor inputs.
"""
# --- Simulated state ---
current_state = "north_south_green"
seconds_elapsed = 32
emergency_vehicle_detected = False
pedestrian_button_pressed = True
# --- Emergency override ---
if emergency_vehicle_detected:
print("EMERGENCY: All directions RED")
print("Emergency vehicle corridor: GREEN")
# --- Normal cycle with timing ---
elif current_state == "north_south_green":
if seconds_elapsed >= 30:
print("North-South: switching to YELLOW")
print("Next state: north_south_yellow")
else:
print(f"North-South: GREEN ({30 - seconds_elapsed}s remaining)")
elif current_state == "north_south_yellow":
if seconds_elapsed >= 5:
print("North-South: switching to RED")
if pedestrian_button_pressed:
print("Pedestrian walk signal: ACTIVATED")
print("Next state: pedestrian_crossing")
else:
print("Next state: east_west_green")
else:
print(f"North-South: YELLOW ({5 - seconds_elapsed}s remaining)")
elif current_state == "east_west_green":
if seconds_elapsed >= 30:
print("East-West: switching to YELLOW")
print("Next state: east_west_yellow")
else:
print(f"East-West: GREEN ({30 - seconds_elapsed}s remaining)")
elif current_state == "pedestrian_crossing":
if seconds_elapsed >= 20:
print("Pedestrian signal: DON'T WALK")
print("Next state: east_west_green")
elif seconds_elapsed >= 15:
print("Pedestrian signal: FLASHING (hurry up!)")
else:
print(f"Pedestrian signal: WALK ({15 - seconds_elapsed}s remaining)")
else:
print(f"ERROR: Unknown state '{current_state}'")
print("Defaulting to ALL RED for safety")
Expected output (with default values):
North-South: switching to YELLOW
Next state: north_south_yellow
The Key Insight
Two levels of conditionals work together:
- Level 1: Which state is the intersection in? (
matchoncurrent_state) - Level 2: Within that state, what should happen? (time-based and sensor-based conditions)
The emergency vehicle check at the top is a priority override — it bypasses the normal cycle entirely. This is a common pattern: check for exceptional conditions first, then handle the normal flow.
Notice the else at the bottom: "Unknown state" with a default to ALL RED. This is defensive programming — if something goes wrong that the programmer didn't anticipate, the system fails safely (all red) rather than dangerously (conflicting greens). You'll see this principle throughout this course, especially in Chapter 11 (Error Handling).
Real-World Complexity
Actual traffic controllers handle much more: left-turn arrows, sensor loops embedded in the pavement (detecting cars waiting), time-of-day schedules (longer greens during rush hour), coordination with adjacent intersections (the "green wave" that lets you hit green lights in sequence if you drive the speed limit), and network connectivity for central monitoring. But every one of these features is implemented with conditional logic.
System 3: The Recommendation Engine
What You See
You finish watching a sci-fi movie on a streaming service. The platform immediately suggests three more movies you might like. One of them looks perfect. How did it know?
What's Happening
Modern recommendation engines use machine learning, but the output of those ML models is still fed through conditional logic to generate the final recommendations. Here's a simplified version of the decision process:
"""
Simplified recommendation engine logic.
Real systems use collaborative filtering and ML models.
"""
# --- User profile (simulated) ---
preferred_genres = ["sci-fi", "thriller", "documentary"]
watch_history = ["Interstellar", "Blade Runner 2049", "Arrival"]
time_of_day = 22 # 10 PM (24-hour format)
is_weekend = True
parental_controls = False
subscription_tier = "premium"
# --- Candidate movie ---
movie_title = "Dune: Part Two"
movie_genre = "sci-fi"
movie_rating = "PG-13"
movie_length_min = 166
is_exclusive = True # Premium-only content
# --- Decision logic ---
genre_match = movie_genre in preferred_genres
already_watched = movie_title in watch_history
time_appropriate = True # Default
# Late-night filtering for long movies
if time_of_day >= 23 and movie_length_min > 120 and not is_weekend:
time_appropriate = False
# Parental controls check
if parental_controls and movie_rating in ["R", "NC-17"]:
eligible = False
reason = "Blocked by parental controls"
elif is_exclusive and subscription_tier != "premium":
eligible = False
reason = "Premium subscription required"
elif already_watched:
eligible = False
reason = "Already in watch history"
elif not genre_match:
eligible = False
reason = "Genre mismatch"
elif not time_appropriate:
eligible = False
reason = "Too long for this time of night on a weekday"
else:
eligible = True
reason = "Matches preferences"
# --- Output recommendation decision ---
if eligible:
print(f"RECOMMEND: {movie_title}")
print(f" Genre: {movie_genre} (matches your preferences)")
print(f" Why: {reason}")
# Confidence level based on how many signals match
signals = 0
if genre_match:
signals += 1
if any(movie_genre == "sci-fi" for _ in watch_history):
signals += 1
if is_weekend and time_of_day >= 19:
signals += 1
if signals >= 3:
confidence = "HIGH"
elif signals >= 2:
confidence = "MEDIUM"
else:
confidence = "LOW"
print(f" Confidence: {confidence}")
else:
print(f"SKIP: {movie_title}")
print(f" Reason: {reason}")
Expected output:
RECOMMEND: Dune: Part Two
Genre: sci-fi (matches your preferences)
Why: Matches preferences
Confidence: HIGH
The Key Insight
The recommendation logic combines several conditional patterns:
-
Exclusion filters (parental controls, subscription tier, already watched): These eliminate movies that should never be shown, regardless of preference match.
-
Preference matching (genre, watch history): These determine relevance.
-
Contextual adjustment (time of day, weekend): These modify recommendations based on situation.
-
Confidence scoring (counting matching signals): Conditionals aren't just for yes/no — they can accumulate evidence.
This layered approach — filter, match, adjust, score — is how real recommendation systems work, even when the matching step uses ML instead of simple genre comparison.
The Common Thread
All three systems share the same fundamental structure:
| System | Input | Decision Logic | Output |
|---|---|---|---|
| ATM | Card, PIN, amount | Validation chain (if-elif-else) | Dispense cash or error |
| Traffic light | Current state, time, sensors | State-based conditions | Next light color |
| Recommendation | User profile, movie data | Multi-factor filtering | Show or skip |
And all three rely on the same principles you learned in Chapter 4: - Order matters: Check the most critical conditions first (authentication before balance check; emergency vehicles before normal cycle) - Boolean operators combine conditions: "Is it late AND a long movie AND a weekday?" - Default cases handle the unexpected: Unknown states, unrecognized inputs, edge cases - Nesting encodes dependent decisions: Only check the PIN if the card is valid; only score confidence if the movie is eligible
Discussion Questions
-
In the ATM example, why is the PIN check done before the balance check? What would happen if the order were reversed — would it be a security risk?
-
The traffic light controller uses an
elseclause that defaults to all-red and prints an error. Why is "fail safely" a better design principle than "fail silently" (doing nothing) or "fail optimistically" (defaulting to all-green)? -
The recommendation engine uses multiple Boolean variables (
genre_match,already_watched,time_appropriate) that are computed before the mainif-elif-elsechain. Why not compute them inline? What are the readability trade-offs? -
All three systems would benefit from loops (to handle multiple transactions, continuous light cycling, or scoring multiple movies). Based on what you know so far, how would you describe the limitation of "single-pass" conditional logic?
-
Pick a technology you use daily (phone alarm, autocorrect, playlist shuffle, thermostat). Sketch the conditional logic that might power its core decision. What conditions does it check? In what order?
Mini-Project
Choose one of the three systems from this case study and extend it:
- ATM: Add a transfer feature (transfer money between checking and savings), a balance inquiry option, and a PIN change option. Use
match/casefor the main menu. - Traffic light: Add a "rush hour mode" that extends green time for the main road. Add a "night mode" that switches to flashing yellow after 11 PM.
- Recommendation: Add a "mood" parameter (action, relaxing, educational) and adjust recommendations based on mood + genre + time of day.