By the end of this lesson, you will be able to control program flow in Python using if, elif, and else statements to make decisions based on data conditions.
What it is
Conditional statements allow a program to execute different blocks of code depending on whether specific conditions are true or false. In Python, this is achieved through branching logic. The core mental model is a decision tree: the program evaluates an expression; if it returnsTrue, the associated block runs; otherwise, it moves to the next condition or skips to the default action. Key terms include condition (the boolean expression being tested), block (the indented code executed when the condition is met), and branching (the process of choosing between paths).
Why it matters
- Data Cleaning: Handle missing values by replacing them with defaults only when they exist.
- Feature Engineering: Create new categorical variables based on numerical thresholds (e.g., "High Income" vs. "Low Income").
- Model Selection: Choose different algorithms based on dataset size or type.
- Error Handling: Prevent crashes by checking if files exist or if data types match before processing.
- Reporting: Generate dynamic summaries that change wording based on statistical significance.
Syntax or steps
Python uses indentation to define code blocks. The structure follows this pattern: 1. Start withif followed by a condition and a colon (:).
2. Indent the code to run if the condition is true.
3. Optionally add elif (else if) for additional conditions.
4. End with else for any remaining cases.
Note that elif and else are optional, but at least one if is required. Conditions must evaluate to boolean values (True or False).
Example
def categorize_age(age):
if age < 18:
return "Minor"
elif 18 <= age < 65:
return "Adult"
else:
return "Senior"
# Test the function
print(categorize_age(17)) # Output: Minor
print(categorize_age(30)) # Output: Adult
print(categorize_age(70)) # Output: Senior
Part-by-part explanation:
The function categorize_age takes an integer age. The first line checks if age is less than 18. If true, it returns "Minor" and stops execution. If false, it proceeds to the elif block, which checks if the age is between 18 and 64 inclusive. This range check uses chained comparisons, a Pythonic feature. If neither condition is met, the else block executes, returning "Senior". The print statements demonstrate how different inputs trigger different branches.
Common mistakes
- Forgetting the colon: Every
if,elif, andelsestatement must end with a colon (:). Omitting it causes aSyntaxError. - Inconsistent indentation: Python relies on whitespace. Mixing tabs and spaces or failing to indent the block under the condition leads to
IndentationError. - Using assignment instead of comparison: Writing
if x = 5assigns 5 to x rather than checking equality. Use==for comparison. - Overlapping conditions: If multiple conditions could be true, only the first matching block executes. Ensure your logic order reflects priority, or use mutually exclusive ranges.
When to use it
Compare conditional statements with other control structures like loops or vectorized operations in libraries such as Pandas.| Method | Best For | Performance Note |
|---|---|---|
if/elif/else | Simple logic, scalar values, complex nested rules | Fast for small datasets; slow for large arrays due to Python overhead |
Pandas apply() | Row-wise transformations requiring custom functions | Slower than vectorized methods; useful when logic is too complex for simple operators |
Vectorized np.where() | Binary choices across entire columns | Very fast; limited to simple true/false outcomes |
Practice
Guided Exercise: Write a function calledcheck_score that takes a number score. Return "Pass" if the score is 50 or higher, and "Fail" otherwise.
Hint: You only need an if and an else.
Challenge: Modify check_score to return "Distinction" if the score is 90 or higher, "Pass" if it is between 50 and 89, and "Fail" if below 50.
Expected Output: check_score(95) should return "Distinction".
Quick check
Question: What happens if none of theif or elif conditions evaluate to True and there is no else block?
Answer: The program simply continues executing the code after the conditional block without running any of the inner statements.
Summary
Conditional statements are fundamental for introducing logic and decision-making into Python programs. By masteringif, elif, and else, you can handle diverse data scenarios efficiently, though you should consider vectorized alternatives for large-scale data analysis tasks.