๐ Day 08 : Conditionals
๐ฏ Enterprise Objective
Control flow is the brain of programming. Today we master decision-making structures in Python, moving from basic conditional branching to high-performance inline ternaries, structural pattern matching, defensive guard clauses, and complex boolean combinations. Writing clean, flat, and bug-free conditionals is the foundation of high-integrity analytics pipelines.
๐ Strategic Overview
| # | Topic | Key Concept | Core Use Case |
|---|---|---|---|
| 1 | Branching Logic | if / elif / else | Standard decision routing |
| 2 | Inline Conditions | Ternary Expressions | Cleaner conditional assignments |
| 3 | Pattern Matching | match / case (Python 3.10+) | Structural schemas & complex dispatch |
| 4 | Defensive Design | Guard Clauses & Early Returns | Clean, flat code structures |
| 5 | Compound Logic | and / or / not | Complex boolean evaluation |
1. Branching Logic : if / elif / else
Python uses if, elif, and else to control the flow of execution based on boolean conditions. The blocks of code are defined strictly by indentation (usually 4 spaces).
๐ผ Why Data Analysts Care
โข Business Rules: Categorizing a user's age into demographics (e.g., <18 is Minor, 18-65 is Adult).
โข Data Filtering: Determining whether a specific row of data should be included in a final calculation based on specific thresholds.
โ ๏ธ Common Pitfall
== True or == False is redundant. Instead of if user_is_active == True:, simply write if user_is_active:. Python natively evaluates the 'truthiness' of any object.
๐ง Under the Hood
elif chain evaluates conditions sequentially from the top down. The very first condition that evaluates to True will execute its block, and Python will immediately skip the remainder of the chain. Reordering the conditions can completely change the output!
๐งช Concept Checks: Branching Logic
Q1. Write an if/elif/else chain that classifies BMI: <18.5 Underweight, 18.5-24.9 Normal, 25-29.9 Overweight, 30+ Obese. Test with bmi=27.5.
Q2. Write code checking if a year is a leap year: divisible by 4 AND (not by 100 OR by 400). Test 2024, 1900, 2000. Print result for each.
Q3. Write an if that checks multiple conditions: age >= 18 and has_license and not suspended. Test with 3 combinations. Print 'Can drive' or reason why not.
Q4. Show the difference between if/elif/elif (stops at first match) vs three separate if statements (checks all). Test with score=95 matching multiple ranges.
Q5. Write nested if statements: outer checks if number is positive/negative/zero, inner checks if even/odd (for non-zero). Test with -7, 0, 12.
2. Inline Conditions : Ternary Expressions
A ternary expression allows you to assign a value based on a condition in a single line. The syntax is: value_if_true if condition else value_if_false.
๐ผ Why Data Analysts Care
โข List Comprehensions: Applying conditional logic during data transformations: ['Pass' if x > 60 else 'Fail' for x in scores].
โข f-strings: Directly rendering different outputs based on state: f"User is {'Active' if is_active else 'Inactive'}".
โ ๏ธ Common Pitfall
A if cond1 else B if cond2 else C). It severely hurts readability. If you need more than one else if, use a standard block.
๐ง Pro Tip
pass, break, or assignment x = 5) inside the return values of a ternary expression.
๐งช Concept Checks: Ternary Expressions
Q1. Write a ternary expression: status = 'Adult' if age >= 18 else 'Minor'. Test with age=15 and age=25. Print both results.
Q2. Write a nested ternary: classify score as 'A' if s>=90 else 'B' if s>=80 else 'C' if s>=70 else 'F'. Test with 95, 85, 65. Discuss readability.
Q3. Use ternary in a list comprehension: ['even' if x%2==0 else 'odd' for x in range(1,6)]. Print result: ['odd','even','odd','even','odd'].
Q4. Use ternary with function calls: result = process_valid(x) if validate(x) else handle_error(x). Write the helper functions and test.
Q5. Write a ternary for default values: name = user_input if user_input else 'Anonymous'. Compare with name = user_input or 'Anonymous'. Are they equivalent?
3. Pattern Matching : Match-Case (Python 3.10+)
Introduced in Python 3.10, match-case is much more than a switch statement. It enables structural pattern matching, allowing you to match variable types, sequence structures, and dict keys.
๐ผ Why Data Analysts Care
โข API Parsing: When an API returns dictionaries with different schemas based on the event type, match-case routes them perfectly.
โข Complex Dispatch: Replacing huge blocks of elif chains when parsing commands or states.
โ ๏ธ Common Pitfall
match-case does NOT fall through. Once a case is matched and its block executes, the match block terminates. There is no need for break.
๐ง Under the Hood
case _: acts as the ultimate default. It must always be placed at the very bottom of the match block. Furthermore, you can capture variables directly in the case pattern: case [x, y]: print(x).
๐งช Concept Checks: Pattern Matching
Q1. Write a match/case for HTTP status codes: 200โ'OK', 404โ'Not Found', 500โ'Server Error', _โ'Unknown'. Test with 4 codes.
Q2. Use match/case with pattern matching on a tuple: match (x, y): with cases (0,0)โ'origin', (x,0)โ'x-axis', (0,y)โ'y-axis', _โ'other'.
Q3. Use match/case with | for OR patterns: case 'GET' | 'HEAD': โ 'read', case 'POST' | 'PUT': โ 'write'. Test all methods.
Q4. Use match/case to destructure a dict: match command: case {'action':'move','x':x,'y':y}:. Extract values into variables.
Q5. Use match/case with guard clauses: case x if x > 0: โ 'positive'. Show the difference between guard and simple pattern.
4. Defensive Design : Guard Clauses & Early Returns
A guard clause validates preconditions at the very top of a function and returns or raises an error immediately if they fail. This prevents deep nesting of if statements.
๐ผ Why Data Analysts Care
โข Data Validation: When receiving a messy dataframe or a raw JSON payload, guards instantly reject invalid schemas before the complex processing logic begins.
โข Readability: Code that flows straight down is immensely easier to read than code deeply indented by 5 nested if blocks.
โ ๏ธ Common Pitfall
๐ง Pro Tip
if not valid: return None. The remainder of the function can then safely assume the input is perfectly valid without wrapping it in an else block.
๐งช Concept Checks: Guard Clauses
Q1. Write a guard clause pattern: if not valid_input: return 'Error' at the top of a function. Show how it simplifies nested if/else.
Q2. Write a function process_data(data) with early returns: if Noneโ'No data', if emptyโ'Empty', if too largeโ'Too big', else process. Test all paths.
Q3. Write input validation guards: check type, range, format before processing. validate_age(value) โ return error string or None. Test 5 inputs.
Q4. Refactor deeply nested if/else into flat guard clauses. Before: 4 levels of nesting. After: 4 sequential if return statements. Show both versions.
Q5. Use assert as a development guard: assert isinstance(x, int), 'x must be int'. Show it raises AssertionError. Explain when to use vs exceptions.
5. Compound Logic : Complex Conditions
Python utilizes and, or, and not to combine multiple conditions. Parentheses should be used to explicitly group conditions when mixing operators.
๐ผ Why Data Analysts Care
โข Advanced Filtering: Filtering a dataframe based on multiple columns (e.g., is_active and (revenue > 1000 or months_tenure > 12)).
โข Aggregating conditions: Using all(list) to verify that an entire batch of data passed quality checks.
โ ๏ธ Common Pitfall
and sequence as soon as it hits a False, and stops checking an or sequence as soon as it hits a True. Do not put side-effects inside conditions!
๐ง Under the Hood
0 < x < 10. This is mathematically elegant and evaluates to x > 0 and x < 10 automatically.
๐งช Concept Checks: Complex Conditions
Q1. Write a function classify_triangle(a,b,c) returning: 'invalid' (triangle inequality), 'equilateral', 'isosceles', 'scalene'. Test with 5 triangles.
Q2. Write a function grade_calculator(scores) that: validates all scores are 0-100, computes weighted average, returns letter grade and pass/fail.
Q3. Write a function ticket_price(age, day, is_member) with complex pricing: kids/adults/seniors ร weekday/weekend ร member discount. Return price and breakdown.
Q4. Write a function validate_password(pw) checking 6 rules (length, upper, lower, digit, special, no spaces). Return (True/False, [failures]). Test 5 passwords.
Q5. Write a function tax_calculator(income, filing_status) using progressive tax brackets with different rates per bracket. Return tax owed and effective rate.
๐ ๏ธ Professional Practice Tasks
Theory is useless without muscle memory. Complete these tasks to solidify your understanding.
Task 1 (ATM Simulator): Write ATM logic: check PIN (3 attempts, lockout), check balance, withdraw (check sufficient funds, daily limit), deposit. Print transaction receipt.
Task 2 (Rock Paper Scissors): Write full game: validate input, determine winner (player vs random), track score over 5 rounds. Print round-by-round results and final winner.
Task 3 (Email Router): Write route_email(email) that classifies by: domain (.eduโacademic, .govโgovernment, .comโcommercial), sender patterns, keywords in subject. Return routing decision.
Task 4 (Discount Engine): Write calculate_discount(customer_type, order_total, coupon_code, is_holiday) with layered rules: base discount + coupon + holiday bonus + loyalty tier. Cap at 50%. Print breakdown.
Task 5 (Data Validator): Write validate_record(record, rules) where rules define: required fields, type checks, range checks, pattern checks, cross-field checks. Return (valid, [errors]).
๐ป Pure Coding Interview Questions
Solve these 25 purely code-based problems.
Q1.
Write a function fizzbuzz(n) printing 1-n with: 'Fizz' for multiples of 3, 'Buzz' for 5, 'FizzBuzz' for both. Do it with minimal if statements.
Q2.
Write a function roman_to_int(s) converting 'XIV' โ 14. Handle subtractive cases (IV=4, IX=9). Use dict mapping.
Q3.
Write a function valid_parentheses(s) checking if brackets ()[]{} are properly matched. Use a stack. Return True/False.
Q4.
Write a function binary_search(lst, target) returning index or -1. Implement with while loop and conditional comparisons.
Q5.
Write a function merge_intervals(intervals) merging overlapping intervals. Sort first, then conditionally merge. Return merged list.
Q6.
Write a function can_jump(nums) determining if you can reach the last index from first. [2,3,1,1,4]โTrue, [3,2,1,0,4]โFalse.
Q7.
Write a function eval_rpn(tokens) evaluating Reverse Polish Notation: ['2','3','+','4','*'] โ 20. Use stack + conditionals.
Q8.
Write a function longest_valid_parens(s) finding length of longest valid parentheses substring. '(()' โ 2.
Q9.
Write a function trap_rain_water(heights) computing trapped water between bars. Use two-pointer approach with conditionals.
Q10.
Write a function word_ladder_length(begin, end, word_list) finding shortest transformation. BFS with character-change conditions.
Q11.
Write a function search_rotated(nums, target) searching in a rotated sorted array. Modified binary search with conditionals.
Q12.
Write a function decode_ways(s) counting ways to decode digit string (1=A, 26=Z). '226' โ 3. DP with conditionals.
Q13.
Write a function state_machine(s) validating a number string handles: spaces, sign, digits, decimal, exponent. Conditional transitions.
Q14.
Write a function calculator(expression) parsing '3 + 4 * 2 / (1 - 5)' respecting precedence. Stack-based with conditionals.
Q15.
Write a function next_greater_element(nums) finding next greater element for each position. Use monotonic stack.
Q16.
Write a function game_of_life(board) computing next state of Conway's Game of Life. Count neighbors, apply rules conditionally.
Q17.
Write a function min_coins(coins, amount) finding minimum coins for amount. DP with conditional updates. Return -1 if impossible.
Q18.
Write a function partition_labels(s) partitioning string into max parts where each letter appears in at most one part.
Q19.
Write a function task_scheduler(tasks, n) finding min intervals to execute all tasks with cooldown n between same tasks.
Q20.
Write a function is_valid_bst(tree_list) checking if list representation of binary tree is a valid BST. Recursive with range conditions.
Q21.
Write a function stock_buy_sell_k(prices, k) finding max profit with at most k transactions. DP with buy/sell state conditions.
Q22.
Write a function regex_match(s, p) implementing simple regex: . matches any char, * matches zero or more of preceding. DP approach.
Q23.
Write a function candy_distribution(ratings) assigning minimum candies (each child โฅ1, higher rating than neighbor โ more candy).
Q24.
Write a function median_sorted_arrays(nums1, nums2) finding median of two sorted arrays in O(log(min(m,n))) with binary search + conditionals.
Q25.
Write a function skyline(buildings) computing city skyline from building rectangles [left,right,height]. Line sweep with conditions.
๐ Day 8 Executive Summary
| Topic | Focus Area | Professional Application |
|---|---|---|
| 1 | if/elif/else | Establishing core routing and categorization logic. |
| 2 | Ternary | Cleaning up simple conditions inside functional map statements. |
| 3 | Match-Case | Parsing complex dictionary schemas or abstract syntax trees. |
| 4 | Guards | Building robust functions that reject invalid data immediately. |
| 5 | Complex | Executing heavy quality assurance pipelines utilizing all/any. |
โ Instructor's End-of-Day Checklist
โข [ ] I rely on Python's native truthiness checking instead of == True.
โข [ ] I implement guard clauses to return early and prevent deep indentation.
โข [ ] I can seamlessly apply ternary operators inside comprehensions.
โข [ ] I understand how match-case utilizes the case _: wildcard.
โข [ ] I have successfully completed all 5 professional practice tasks.
โข [ ] I have reviewed, coded, and internalized all 25 pure coding interview questions.