Python: lesson 4 of 7

Python

PATH 01MODULE 02LESSON 04 OF 07Next: Loops in Python

Conditional Statements

Use if, elif, and else to make clear decisions from data values and rules.

Beginner13 min readpythonconditionalsboolean-logicdata-validation

Concept

Conditional statements let code choose a path based on a Boolean expression. Python uses if for the first condition, elif for an additional condition, and else for the remaining case. Indentation defines which lines belong to each branch.

Why It Matters

Data workflows often need explicit rules: flag an invalid age, assign a customer-risk band, or decide whether a model score crosses an operating threshold. Conditions let you express those rules in code, where they can be reviewed and tested.

Intuition

Think of an if statement as a decision tree with a small number of branches. Python asks a question, runs the indented code under the first true answer, and skips the other branches.

Basic if, elif, and else

fraud_probability = 0.82

if fraud_probability >= 0.80:
    risk_level = "high"
elif fraud_probability >= 0.50:
    risk_level = "medium"
else:
    risk_level = "low"

print(risk_level)

Expected output:

high

Python checks from top to bottom. Because 0.82 satisfies the first condition, the elif and else branches do not run.

Real-World / Data Science Example

Before using a customer age in a simple analysis, validate the value.

customer_age = None

if customer_age is None:
    message = "Age is missing"
elif customer_age < 0 or customer_age > 120:
    message = "Age is invalid"
else:
    message = "Age is ready for analysis"

print(message)

Expected output:

Age is missing

This distinguishes a missing value from an implausible value. They may need different cleaning decisions.

Nested Conditions and Readability

You can put a condition inside another condition, but deep nesting becomes hard to follow. Prefer a clear sequence of checks or compute descriptive Boolean variables first.

income = 70000
has_late_payment = False

has_sufficient_income = income >= 50000
is_low_risk = has_sufficient_income and not has_late_payment

if is_low_risk:
    decision = "review with standard process"
else:
    decision = "request more information"

Technical Explanation

Every condition must produce something Python can interpret as true or false. elif is optional and can appear more than once; else is optional and has no condition. A colon follows each if, elif, or else line, and the block beneath it must be consistently indented.

Explanation of the Code

The risk example orders its checks from the most restrictive threshold to the least restrictive. The validation example checks None before numeric comparisons, preventing an attempt to compare None to a number.

When to Use It

Use conditionals for small decisions, validation rules, labels, and branching workflow logic. If you are making the same decision for every row in a large Pandas table, you will often use vectorized operations later instead of a Python if inside a row loop.

Failure Signals

Common Mistakes

  1. Forgetting the colon after an if line.
  2. Using inconsistent indentation.
  3. Checking a numeric range before checking whether a value is missing.
  4. Writing overlapping conditions in the wrong order.
  5. Creating deeply nested branches that hide the business rule.

Best Practices

Place exceptional or missing cases first when they would otherwise break later comparisons. Give complicated conditions a descriptive variable name. Keep each branch focused on one outcome, and test boundary values such as exactly 0.80 for a threshold.

Data Science Perspective

Conditional logic appears in data cleaning, feature engineering, eligibility rules, and model decision thresholds. Later, Pandas conditions produce Boolean masks for entire columns; understanding a single if makes those larger operations easier to reason about.

Interview Perspective

Question: Why should threshold conditions be ordered carefully? A strong answer: overlapping conditions are evaluated top to bottom, so a broad condition placed first can make a later, more specific branch unreachable.

Worked Example: Boundaries Are Part of the Rule

State what happens at the exact threshold, not only above and below it.

model_score = 0.70
approval_threshold = 0.70

if model_score >= approval_threshold:
    outcome = "approve"
else:
    outcome = "review"

print(outcome)

Expected output: approve. A one-character choice between > and >= can change real decisions, so write the requirement in plain language before encoding it.

Practice Questions

  1. Label an order as "large" when its amount is at least 500, otherwise "standard".
  2. Write validation logic for a missing or negative transaction amount.
  3. A model score is exactly 0.70. Explain which branch runs if the rule uses >= 0.70.

Quick Quiz

  1. What follows an if condition line? Answer: a colon.
  2. Can an if statement have multiple elif branches? Answer: yes.
  3. Which is safer before age < 18: checking age is None or comparing first? Answer: checking None first.

Key Takeaway

Key Takeaways

Conditionals make data rules explicit. Order conditions carefully, handle missing values deliberately, and use clear Boolean names to avoid unreadable nesting.

Next Lesson

Next, learn how loops repeat work across values, features, and records.

Finish this lesson on your terms

Mark it complete when you have worked through the material and are ready to move on.