CATEGORY 6 OF 13

Conditionals & Logic

Master the decision-making building blocks of programming: if/else chains, boolean logic, guard clauses, switch statements, and validation patterns that make your code correct and readable.

Time: O(1) per branch evaluation
Space: O(1)

Learn & Reference

Understanding the Pattern

Conditionals & Logic

Every program makes decisions. Conditionals let your code choose different paths based on data. While the syntax is simple, writing clear, correct conditional logic is a skill that separates clean code from buggy code.

Core Constructs

If / Else If / Else

The fundamental branching mechanism. Test conditions in order — the first matching branch executes. Use else as a catch-all fallback. Order matters: put the most specific conditions first.

Boolean Operators

Combine conditions with and/&&, or/||, and not/!. Know the precedence: not > and > or. Use parentheses when in doubt.

Short-Circuit Evaluation

In a && b, if a is false, b is never evaluated. In a || b, if a is true, b is skipped. This is useful for guard clauses like if (arr != null && arr.length > 0).

Switch / Match

Use switch (JS/TS/Java/Go) or match (Python 3.10+) for multi-way branching on a single value. Cleaner than long if/else chains when comparing against discrete values.

Ternary Operator

A one-line conditional: condition ? valueIfTrue : valueIfFalse (JS/TS/Java/Go) or value_if_true if condition else value_if_false (Python). Keep it simple — nested ternaries are unreadable.

Design Patterns

Guard Clauses

Handle edge cases early and return, rather than wrapping the main logic in a deep if block. This flattens your code and makes the "happy path" obvious.

Validation First

Check inputs at the top of a function: null checks, range checks, type checks. Fail fast with clear errors rather than propagating bad data.

Exhaustive Handling

Cover all possible cases. Use else/default branches even if you think they're unreachable — they catch bugs and document intent.

Common Mistakes

  1. Using = instead of ==: Assignment vs comparison is a classic bug in C-family languages. Python avoids this since = in a condition is a syntax error
  2. Forgetting operator precedence: a || b && c is a || (b && c), not (a || b) && c. Always use parentheses with mixed operators
  3. Not handling all cases: Missing an else/default branch leaves undefined behavior. Always think "what happens if none of my conditions match?"
  4. Overly nested conditionals: Deep nesting is hard to read. Refactor with guard clauses or extract helper functions
  5. Comparing floats with ==: Floating-point rounding means 0.1 + 0.2 != 0.3. Use a tolerance: abs(a - b) < epsilon

When to Use

Classify input into categories (grades, types, ranges)
Validate input before processing
Implement rules with multiple conditions
Handle edge cases at boundaries
Build state machines or game logic
Parse structured input with format rules

Template

1# Conditionals & Logic
2# if / elif / else — multi-way branching
3# and / or / not — boolean operators
4# Ternary: result = x if cond else y
5
6def solve(value):
7 if value > 0:
8 return "positive"
9 elif value == 0:
10 return "zero"
11 else:
12 return "negative"
{ }

Syntax Reference

1# === If / Elif / Else ===
2if x > 0:
3 print("positive")
4elif x == 0:
5 print("zero")
6else:
7 print("negative")
8
9# === Boolean operators ===
10a and b # True if both True
11a or b # True if either True
12not a # negate
13x is None # identity check (not ==)
14
15# === Ternary ===
16result = "yes" if condition else "no"
17
18# === Match (Python 3.10+) ===
19match command:
20 case "start":
21 begin()
22 case "stop":
23 end()
24 case _:
25 unknown()
26
27# === Truthiness ===
28# Falsy: None, False, 0, 0.0, "", [], {}, set()
29# Everything else is truthy
30if my_list: # checks non-empty
31if not value: # checks falsy
32
33# === Chained comparisons ===
34if 0 < x < 100: # unique to Python
35if a == b == c: # all equal
36
37# === any / all ===
38any(x > 0 for x in arr) # at least one positive
39all(x > 0 for x in arr) # all positive
📋

Common Recipes

1# --- Guard Clause Pattern ---
2def process(data):
3 if data is None:
4 return None
5 if len(data) == 0:
6 return []
7 # main logic here
8 return [x * 2 for x in data]
9
10# --- Range Classification ---
11def classify_grade(score):
12 if score >= 90:
13 return "A"
14 elif score >= 80:
15 return "B"
16 elif score >= 70:
17 return "C"
18 elif score >= 60:
19 return "D"
20 else:
21 return "F"
22
23# --- Validation Pattern ---
24def validate_age(age):
25 if not isinstance(age, int):
26 raise TypeError("age must be int")
27 if age < 0 or age > 150:
28 raise ValueError("age out of range")
29 return True
30
31# --- Leap Year Check ---
32def is_leap_year(year):
33 return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
O(n)

Complexity

ConstructTimeNotes
Single if/elseO(1)Constant-time branch
If/elif chain (k branches)O(k)Each condition checked sequentially
Switch/matchO(1)Jump table or hash dispatch in most languages
Nested conditionals (d levels)O(d)Depth of nesting
Boolean expressionO(1)Short-circuit evaluation
Validation (k checks)O(k)Linear in number of checks

Watch Out

  • Using = instead of ==: Assignment vs comparison is a classic bug in C-family languages. Python avoids this since `=` in a condition is a syntax error
  • Forgetting operator precedence: `a || b && c` is `a || (b && c)`, not `(a || b) && c`. Always use parentheses with mixed operators
  • Not handling all cases: Missing an else/default branch leaves undefined behavior. Always think "what happens if none of my conditions match?"
  • Overly nested conditionals: Deep nesting is hard to read. Refactor with guard clauses or extract helper functions
  • Comparing floats with ==: Floating-point rounding means `0.1 + 0.2 != 0.3`. Use a tolerance: `abs(a - b) < epsilon`