if Statements & Single Conditions — Branching, Predicates, and Guard Rails
Overview
if is how Python chooses what runs next: evaluate a condition, and if it is truthy, execute the indented block. In data work you use the same idea for validating ETL rows, SLA checks, pipeline readiness, file-format gates, and HTTP status handling. Here, single condition means one decision expression for one if gate—not necessarily one comparison. That expression may deliberately combine predicates with and, or, or in, plus else when both outcomes must be explicit.
The Practice Lab if Statements & Single Conditions (Segment 3: Control Flow) walks through five patterns: a threshold with no else, a boundary comparison with <=, a conjunction with and, a disjunction with or and else, and a whitelist with in and a set literal.
Use the flow diagram for decision structure (including the classic or pitfall). Open the practice map for Q1–Q5 code aligned with the autograder.
Enable JavaScript to explore the interactive diagram.
Map to Practice Lab questions
| Lab Q | Skill |
|---|---|
| Q1 | if row_value > 0: → print("Valid") — no output when false |
| Q2 | if actual_time <= 5: → print("SLA Met") — boundary inclusive |
| Q3 | if schema_ready and data_loaded: → print("Ready to run") — keyword and, not & |
| Q4 | if fmt == "csv" or fmt == "parquet": … else: — two comparisons; never or "parquet" alone |
| Q5 | if status_code in {200, 201, 204}: … else: — in for membership; == to the set is wrong |
Practice here: Practice Lab → if Statements & Single Conditions.
Enable JavaScript to explore the interactive diagram.
Syntax essentials
| Piece | Rule |
|---|---|
| Colon | if condition: — missing : → SyntaxError |
| Indent | Body is one indented block (conventionally 4 spaces) |
| No body | Empty block needs pass |
| Comparison | == tests equality; = is assignment (illegal in if) |
Industry norms
| Practice | Why |
|---|---|
| Name booleans positively | is_valid reads better than not_invalid in nested logic |
Prefer in over long or chains | Lists, tuples, and sets all express membership; a set communicates unique whitelist values and has fast average-case lookup |
| Explicit comparisons | if x == True: is redundant; use if x: only when x is already boolean |
| Guard clauses | if not row: return flattens happy-path code in services |
| Tests for boundaries | SLA and money use <= / >= deliberately — off-by-one bugs are expensive |
| Spark/SQL | Row logic becomes CASE WHEN, WHERE, isin — same predicates, different execution model |
Key takeaways
- A lone
ifwith noelsemeans “do nothing” when the condition is false — valid for optional logging or validation flags. and/orshort-circuit: later sub-expressions may not run — rely on this forif x is not None and x.name:style guards.if fmt == "csv" or "parquet":is always true — non-empty strings are truthy; comparefmteach time.200 == {200, 201, 204}is False;200 in {200, 201, 204}is True.- A list, tuple, or set can be used with
in. The lab accepts all three; its reference answer uses a set because a whitelist contains unique accepted values. &/|on integers are bitwise; useand/orfor boolean logic in Python.
Examples
Example 1 — Q1: valid ETL row
row_value = 7
if row_value > 0:
print("Valid")
Output:
Valid
Example 2 — Q2: SLA fallback
actual_time = 6
if actual_time <= 5:
print("SLA Met")
else:
print("SLA Breached")
Output:
SLA Breached
Example 3 — Q3: pipeline ready (both flags)
schema_ready = True
data_loaded = False
if schema_ready and data_loaded:
print("Ready to run")
else:
print("Not ready")
Output:
Not ready
Example 4 — Q4: supported format
fmt = "parquet"
if fmt == "csv" or fmt == "parquet":
print("Supported")
else:
print("Unsupported")
Output:
Supported
Example 5 — Q5: HTTP status whitelist
status_code = 404
if status_code in {200, 201, 204}:
print("OK")
else:
print("Error")
Output:
Error
Example 6 — Production-shaped: guard + happy path
def process_batch(rows):
if not rows:
return {"processed": 0, "status": "skipped"}
if len(rows) > 10_000:
raise ValueError("batch too large")
# main path stays shallow
return {"processed": len(rows), "status": "ok"}
Example 7 — Production-shaped: configurable SLA hours
SLA_HOURS = 5
def sla_label(actual_hours: float) -> str:
if actual_hours <= SLA_HOURS:
return "SLA Met"
return "SLA Miss"
Mistakes
Mistake 1 — Missing : or indentation
❌ if x > 0 without colon, or print not indented.
✅ if x > 0: with a four-space body.
Mistake 2 — < instead of <= for “within 5”
❌ actual_time < 5 rejects exactly 5 hours.
✅ actual_time <= 5 (Lab Q2).
Mistake 3 — & instead of and
❌ schema_ready & data_loaded — bitwise on bools can seem to work but is the wrong idiom and fails for non-integers.
✅ schema_ready and data_loaded (Lab Q3).
Mistake 4 — if fmt == "csv" or "parquet":
❌ Second operand is always truthy — branch always runs.
✅ fmt == "csv" or fmt == "parquet" (Lab Q4).
Mistake 5 — == instead of in for membership
❌ status_code == {200, 201, 204} is False for 200.
✅ status_code in {200, 201, 204} (Lab Q5).
Mistake 6 — Forgetting else when output is required
❌ Unsupported formats produce no line if you only handle the happy path.
✅ Add else: when the spec requires a message (Lab Q4, Q5).
Interview
Q1. What is short-circuit evaluation?
For a and b, if a is false, b is not evaluated. For a or b, if a is true, b is not evaluated. Used for safe patterns like if obj and obj.id:.
Q2. When is if x: preferred over if x is not None:?
if x: treats None, 0, "", and [] as false — good for “has useful value.” Use is None when 0 or [] are valid states you must distinguish from missing.
Q3. How does SQL express the same ideas?
WHERE filters rows (like keeping only branches that “run”). CASE WHEN … THEN … ELSE … END labels rows (like assigning an outcome per row). IN (200, 201, 204) matches Python in.
Q4. PySpark equivalent of if / else on a column?
F.when(condition, value).otherwise(other) or chained .when. For membership, F.col("c").isin(200, 201, 204).
Python vs PySpark
On the driver, Python if runs once per control-flow path. On Spark, column expressions apply per row in parallel. The comparison table is generated for this topic. Use Try Now for Python and PySpark practice.
Python vs SQL
SQL states predicates and projections declaratively; Python if runs imperatively statement by statement. WHERE vs CASE mirrors filter vs label. The comparison table is generated for this topic. Use Try Now for Python and SQL practice.