DSM
50 XP
25 minsBeginner50 XP

Conditionals

So far your programs run every line, top to bottom, no exceptions. Real programs choose. Should this transaction be flagged? Is this value an outlier? Does this row pass validation? Today your code learns to ask questions and act on the answers.

What you'll learn

  • Write if, elif, and else blocks with correct indentation
  • Combine comparisons with and, or, and not inside conditions
  • Order elif branches so the most specific test runs first
  • Use truthiness to test for empty strings and zero values
  • Replace nested conditionals with guard clauses for readability

What

A conditional runs a block of code only when a boolean condition is True. Python gives you if for the first test, elif for follow-up tests, and else for everything that falls through.

Why

Every data pipeline is full of decisions: skip bad rows, cap outliers, route records, pick a default when a value is missing. Without conditionals, code can't respond to the data it sees.

Where it's used

Data validation rules, feature engineering (bucketing ages into groups), alert thresholds, handling missing values, and every filter you'll ever write.

Where this runs in production

StripePayment risk rules

Before ML models score a transaction, hard rules run first: if the card country and IP country differ AND the amount exceeds a threshold, route to review. Pure if/elif logic.

DuolingoStreak notifications

If a learner hasn't practised today and their streak is at risk and it's evening in their timezone, send the reminder — three conditions joined with and.

ZillowListing quality gates

A new listing is auto-published only if it has photos, a valid price, and a complete address; otherwise it's queued for manual review via an else branch.

Theory

The core ideas, in plain language.

An if statement has three parts: the keyword if, a condition that evaluates to True or False, and a colon. The indented lines below it form the block that runs when the condition holds. Indentation is not decoration in Python — it IS the syntax that defines where a block starts and ends.
temperature = 39.2
if temperature > 38.0:
    print('Fever detected')
    print('Flag for review')
print('Check complete')

The two indented lines run only when temperature > 38.0. The final print is not indented, so it runs every time. Standard indentation is 4 spaces — pick it and never mix tabs and spaces.

Analogy: The airport security lane

Think of if/elif/else as an airport security officer routing passengers: 'Priority ticket? Lane 1. No? Crew badge? Lane 2. No? Everyone else, lane 3.' Each passenger is checked against the rules top to bottom and takes the FIRST lane that matches — nobody is checked against later rules once they've been routed.

Key Concept
elif chains: first match wins

Python evaluates if/elif conditions top to bottom and runs ONLY the first block whose condition is True — then skips the rest of the chain entirely. Order matters: put the most specific condition first, or a broader condition above it will swallow every case.

score = 91
if score >= 90:
    grade = 'A'
elif score >= 80:
    grade = 'B'
elif score >= 70:
    grade = 'C'
else:
    grade = 'F'
print(grade)  # A

score is 91, so the first condition matches and grade is 'A'. Even though 91 >= 80 is also True, that branch never runs. If you reversed the order (>= 70 first), every passing score would be 'C' — a classic ordering bug.

Conditions are just boolean expressions — everything from the Operators lesson applies. Combine tests with and (both must hold), or (at least one must hold), and not (flips the result). Parentheses make grouped logic explicit and readable.
Watch out
The assignment-in-condition trap

Writing `if x = 5:` is a SyntaxError — a single = assigns, a double == compares. Also watch for `if x == 5 or 6:` which does NOT mean 'x is 5 or 6'; it means '(x == 5) or (6)', and 6 is always truthy, so the condition is always True. Write `if x == 5 or x == 6:` or `if x in (5, 6):`.

Visual Learning

See the concept, then explore it.

How an if/elif/else chain routes a value

Follow a transaction amount through the chain. Click each node to see what happens there.

Worked Examples

Watch it built up, one line at a time.

Very EasyA single if

Warn when a website's response time is slow.

Step 1 of 2

The measured response time in milliseconds. An int, as you'd get from a monitoring tool.

Code
01response_ms = 850
Practice Coding

Your turn — write the code.

Your task

An online store calculates shipping. Complete the rules: orders of $100 or more ship free; orders of $50–99.99 ship for $5; everything below $50 ships for $10. Then print the result. Work only with the variables provided.

Expected output
Order: $64.90
Shipping: $5.00
Total: $69.90

Write your solution in the editor on the right, then hit Run.

Exercises

Prove it. Reach 80% to complete the lesson.

Mastery Gate0% / 80% required
Easy0/2 solved

In an if/elif/elif/else chain, how many branches can execute for a single run?

What does this print? x = 0 if x: print('yes') else: print('no')

Medium0/3 solved

A grading chain tests `if score >= 70:` first, then `elif score >= 90:`. What grade does score = 95 get?

ScenarioYou're cleaning survey data. A response is valid when the age field is not None AND is between 13 and 120. You write: if age >= 13 and age <= 120 and age is not None: — and the code crashes on rows where age is None.

Why does it crash, and what's the fix?

A weather station reports wind_speed_kmh = 78. Print the storm category: 'calm' below 20, 'breezy' from 20 to below 60, 'gale' from 60 to below 90, 'storm' at 90 or above.

Correct bucket:78 falls in the 60–89 range, so the output must be gale
Chain order:Conditions must be ordered so each elif implies the previous test failed
Hard0/1 solved

Which condition correctly checks that status is either 'active' or 'trial'?

Complete 80% more exercises to unlock.
Interview Prep

How this shows up in real interviews.

Why does the order of elif branches matter? Give an example of a bug caused by wrong ordering.

Show model answer

Python evaluates an if/elif chain top to bottom and executes only the first branch whose condition is True — every later branch is skipped, even if its condition would also hold. So broader conditions placed early swallow cases meant for more specific branches below. Classic bug: a grading chain that tests score >= 70 before score >= 90 gives every A-student a C, because 95 satisfies the first test and the >= 90 branch becomes unreachable. The rule of thumb is to order branches from most specific to most general, and to design ranges so each elif implicitly relies on the previous tests having failed.

What is a guard clause, and why do many data teams prefer guard clauses to nested if statements?

Show model answer

A guard clause is an early exit at the top of a function that handles an invalid or edge case immediately — 'if the input is None, return an error now' — instead of wrapping the main logic in ever-deeper nested ifs. The benefits are readability and safety: each precondition is checked and dismissed in one line, the happy path ends up at the lowest indentation level where it's easiest to read, and you can't accidentally fall through a forgotten else. In data code, where inputs are routinely missing, malformed, or out of range, functions often start with two or three guards before a single line of real logic runs.

Explain how short-circuit evaluation interacts with conditionals, and how you'd exploit it when a value might be None.

Show model answer

With `a and b`, Python evaluates b only if a is True; with `a or b`, only if a is False. That's short-circuiting, and it means the ORDER of conditions is a correctness tool, not just style. If age might be None, `age is not None and age >= 18` is safe because when the first test fails Python never attempts the comparison that would raise a TypeError; reversed, it crashes on the first None. The same trick guards division (`total > 0 and passed / total > 0.5`) and dictionary access. In interviews, mentioning that you deliberately order conditions to make later ones safe signals real production experience.

Common Mistakes to Avoid

1) Using = instead of == inside a condition — SyntaxError. 2) Writing `if x == 5 or 6:` — always True because 6 is truthy; spell out both comparisons or use `x in (5, 6)`. 3) Ordering elif branches broad-to-specific so specific branches never run. 4) Forgetting the colon after if/elif/else, or mis-indenting the block underneath. 5) Testing floats for exact equality in conditions — compare with a tolerance. 6) Using `if count:` when 0 is a legitimate value — write `if count is not None:` when you mean 'present', not 'non-zero'.

Ask the AI Tutor

Try these prompts in the AI Tutor panel: • 'Quiz me with five if/elif chains and make me predict the output.' • 'Show me a real data-cleaning bug caused by a wrongly ordered elif.' • 'Explain guard clauses with a fresh analogy.' • 'Give me three conditions where truthiness gives a surprising result.' • 'Interview mode: ask me about short-circuit evaluation and grade my answer.'

Glossary

Conditional — a statement that runs code only when a condition is True. Condition — a boolean expression tested by if/elif/while. Block — the indented lines governed by a statement. elif — 'else if': the next test in a chain, checked only if everything above failed. else — the fallback branch when no condition matched. Guard clause — an early exit that handles an edge case before the main logic. Truthiness — Python's rules for treating non-boolean values as True/False in conditions. Short-circuit evaluation — and/or stop evaluating as soon as the result is decided. Nesting — placing a conditional inside another conditional's block.

Recommended Resources

• Docs: 'More Control Flow Tools' in the official Python tutorial — if statements from the source. • Read: PEP 8's indentation rules to see why 4 spaces is the universal standard. • Practice: take any three business rules from an app you use (shipping, discounts, notifications) and write them as if/elif chains in a REPL. • Next in DSM: decisions are one half of control flow — repetition is the other. For Loops teaches your code to process a whole dataset one row at a time.

Recap

✓ if runs a block only when its condition is True; indentation defines the block. ✓ elif chains test top to bottom — the first match wins and the rest are skipped. ✓ else is the fallback when nothing matched; with it, exactly one branch always runs. ✓ Order conditions from most specific to most general. ✓ and/or/not build compound conditions; short-circuiting makes condition order a safety tool. ✓ Guard clauses beat deep nesting: handle bad cases early, keep the happy path flat. Next up: For Loops. You can make one decision — next you'll repeat work across an entire collection, the pattern behind every row-by-row data operation.

scratchpad — preview this lesson's challenge anytime
shipping.pyPython
Ready
Output

Run your code to see the output here.