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.
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
- 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 && cisa || (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
When to Use
Template
1# Conditionals & Logic2# if / elif / else — multi-way branching3# and / or / not — boolean operators4# Ternary: result = x if cond else y56def solve(value):7if value > 0:8return "positive"9elif value == 0:10return "zero"11else:12return "negative"
Syntax Reference
1# === If / Elif / Else ===2if x > 0:3print("positive")4elif x == 0:5print("zero")6else:7print("negative")89# === Boolean operators ===10a and b # True if both True11a or b # True if either True12not a # negate13x is None # identity check (not ==)1415# === Ternary ===16result = "yes" if condition else "no"1718# === Match (Python 3.10+) ===19match command:20case "start":21begin()22case "stop":23end()24case _:25unknown()2627# === Truthiness ===28# Falsy: None, False, 0, 0.0, "", [], {}, set()29# Everything else is truthy30if my_list: # checks non-empty31if not value: # checks falsy3233# === Chained comparisons ===34if 0 < x < 100: # unique to Python35if a == b == c: # all equal3637# === any / all ===38any(x > 0 for x in arr) # at least one positive39all(x > 0 for x in arr) # all positive
Common Recipes
1# --- Guard Clause Pattern ---2def process(data):3if data is None:4return None5if len(data) == 0:6return []7# main logic here8return [x * 2 for x in data]910# --- Range Classification ---11def classify_grade(score):12if score >= 90:13return "A"14elif score >= 80:15return "B"16elif score >= 70:17return "C"18elif score >= 60:19return "D"20else:21return "F"2223# --- Validation Pattern ---24def validate_age(age):25if not isinstance(age, int):26raise TypeError("age must be int")27if age < 0 or age > 150:28raise ValueError("age out of range")29return True3031# --- Leap Year Check ---32def is_leap_year(year):33return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
Complexity
| Construct | Time | Notes |
|---|---|---|
| Single if/else | O(1) | Constant-time branch |
| If/elif chain (k branches) | O(k) | Each condition checked sequentially |
| Switch/match | O(1) | Jump table or hash dispatch in most languages |
| Nested conditionals (d levels) | O(d) | Depth of nesting |
| Boolean expression | O(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`