Skip to content

Conditional Statements (if-else)

Enabling Programs to Make Decisions — Executing Different Code Based on Conditions


What are Conditional Statements?

Conditional statements allow programs to execute different code based on different situations, similar to:

  • Stata: if conditional filtering
  • R: if-else statements
  • Daily life: "If it rains, bring an umbrella; otherwise, don't"

Basic Syntax: if Statement

1. Simple if

python
age = 20

if age >= 18:
    print("You are an adult")
    print("You can vote")

# Output:
# You are an adult
# You can vote

Syntax Points:

  • if is followed by a condition, ending with a colon :
  • Indentation (4 spaces or 1 tab) indicates the code block
  • Indented code executes only when the condition is true

Stata/R Comparison:

stata
* Stata (no true if statement, only conditional filtering)
gen adult = "Adult" if age >= 18
r
# R
if (age >= 18) {
  print("You are an adult")
  print("You can vote")
}

2. if-else (Binary Choice)

python
age = 16

if age >= 18:
    print("You are an adult")
else:
    print("You are a minor")

# Output: You are a minor

Practical Example: Income Classification

python
income = 75000

if income >= 100000:
    category = "High income"
else:
    category = "Low-middle income"

print(f"Income category: {category}")
# Output: Income category: Low-middle income

3. if-elif-else (Multiple Conditions)

python
score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"Grade: {grade}")
# Output: Grade: B

Note:

  • elif is short for "else if"
  • Conditions are checked from top to bottom, stopping once one is met
  • else is optional (catch-all case)

Comparison: Stata vs R vs Python

Stata Approach (Generate Categorical Variable)

stata
* Stata
gen income_group = ""
replace income_group = "Low income" if income < 30000
replace income_group = "Middle income" if income >= 30000 & income < 80000
replace income_group = "High income" if income >= 80000

R Approach

r
# R
if (income < 30000) {
  income_group <- "Low income"
} else if (income < 80000) {
  income_group <- "Middle income"
} else {
  income_group <- "High income"
}

Python Approach

python
# Python
if income < 30000:
    income_group = "Low income"
elif income < 80000:
    income_group = "Middle income"
else:
    income_group = "High income"

Practical Cases

Case 1: Survey Data Validation

python
# Respondent data
age = 25
income = 50000
education_years = 16

# Data validation
print("=== Data Quality Check ===")

# Check age
if age < 0 or age > 120:
    print("✗ Age data abnormal")
elif age < 18:
    print("⚠️  Minor respondent")
else:
    print("✓ Age data normal")

# Check income
if income < 0:
    print("✗ Income data abnormal (negative)")
elif income == 0:
    print("⚠️  Zero income, possibly unemployed")
elif income > 1000000:
    print("⚠️  Income too high, needs verification")
else:
    print("✓ Income data normal")

# Check education years
if education_years < 0 or education_years > 30:
    print("✗ Education years abnormal")
else:
    print("✓ Education years normal")

Case 2: BMI Health Assessment

python
# Calculate BMI
height_m = 1.75
weight_kg = 70
bmi = weight_kg / (height_m ** 2)

# BMI classification and recommendations
print(f"Your BMI: {bmi:.2f}")

if bmi < 18.5:
    category = "Underweight"
    advice = "Recommend increasing nutritional intake"
elif bmi < 25:
    category = "Normal"
    advice = "Maintain current status"
elif bmi < 30:
    category = "Overweight"
    advice = "Recommend moderate exercise and diet control"
else:
    category = "Obese"
    advice = "Recommend consulting a doctor for weight loss plan"

print(f"Category: {category}")
print(f"Advice: {advice}")

Output:

Your BMI: 22.86
Category: Normal
Advice: Maintain current status

Case 3: Academic Performance Assessment

python
# Student data
gpa = 3.7
attendance_rate = 0.95
assignments_completed = 18
total_assignments = 20

# Comprehensive assessment
print("=== Academic Performance Assessment ===")

# GPA assessment
if gpa >= 3.5:
    gpa_level = "Excellent"
elif gpa >= 3.0:
    gpa_level = "Good"
elif gpa >= 2.5:
    gpa_level = "Average"
else:
    gpa_level = "Needs improvement"

# Attendance assessment
if attendance_rate >= 0.9:
    attendance_level = "Excellent"
elif attendance_rate >= 0.75:
    attendance_level = "Good"
else:
    attendance_level = "Needs improvement"

# Assignment completion
completion_rate = assignments_completed / total_assignments
if completion_rate >= 0.9:
    assignment_level = "Excellent"
elif completion_rate >= 0.75:
    assignment_level = "Good"
else:
    assignment_level = "Needs improvement"

# Overall evaluation
if gpa_level == "Excellent" and attendance_level == "Excellent" and assignment_level == "Excellent":
    overall = "⭐ Excellent student"
elif gpa_level == "Needs improvement" or attendance_level == "Needs improvement":
    overall = "⚠️  Needs tutoring"
else:
    overall = "✓ Qualified student"

print(f"GPA: {gpa} ({gpa_level})")
print(f"Attendance rate: {attendance_rate*100:.1f}% ({attendance_level})")
print(f"Assignment completion: {completion_rate*100:.1f}% ({assignment_level})")
print(f"Overall: {overall}")

Nested Conditional Statements

Conditional statements can be nested (having if statements inside if statements).

python
age = 25
income = 75000
has_degree = True

# Nested conditions
if age >= 18:
    if has_degree:
        if income >= 50000:
            eligibility = "Fully qualified"
        else:
            eligibility = "Qualified but income low"
    else:
        eligibility = "Qualified but needs degree"
else:
    eligibility = "Age not qualified"

print(f"Loan eligibility: {eligibility}")
# Output: Loan eligibility: Fully qualified

Better Approach (Avoid Excessive Nesting):

python
age = 25
income = 75000
has_degree = True

# Simplify with logical operators
if age >= 18 and has_degree and income >= 50000:
    eligibility = "Fully qualified"
elif age < 18:
    eligibility = "Age not qualified"
elif not has_degree:
    eligibility = "Needs degree"
elif income < 50000:
    eligibility = "Income not qualified"
else:
    eligibility = "Unknown situation"

print(f"Loan eligibility: {eligibility}")

Conditional Expressions (Ternary Operator)

For simple if-else, you can use one line:

python
# Traditional approach
age = 20
if age >= 18:
    status = "Adult"
else:
    status = "Minor"

# Conditional expression (one line)
age = 20
status = "Adult" if age >= 18 else "Minor"

print(status)  # Adult

Syntax:

python
value_if_true if condition else value_if_false

Practical Examples:

python
# Income classification
income = 120000
category = "High income" if income >= 100000 else "Low-middle income"

# Pass/fail determination
score = 85
result = "Pass" if score >= 60 else "Fail"

# Gender encoding
gender = "Male"
gender_code = 1 if gender == "Male" else 0

print(category, result, gender_code)
# Output: High income Pass 1

Multi-Condition Judgment Techniques

1. Use in to Simplify Multiple or

python
# Verbose approach
major = "Economics"
if major == "Economics" or major == "Finance" or major == "Business":
    print("Business major")

# Concise approach
major = "Economics"
if major in ["Economics", "Finance", "Business"]:
    print("Business major")

2. Use Range Checking

python
# Check if age is in valid range
age = 25

# Python supports chained comparisons
if 18 <= age <= 65:
    print("Working age population")

# Equivalent to (but not recommended)
if age >= 18 and age <= 65:
    print("Working age population")

3. Early Return (In Functions)

python
def check_eligibility(age, income, has_job):
    # Early return for non-qualifying cases
    if age < 18:
        return "Age not qualified"

    if income < 30000:
        return "Income not qualified"

    if not has_job:
        return "Needs employment"

    # All conditions met
    return "Qualified"

result = check_eligibility(25, 50000, True)
print(result)  # Qualified

Common Errors

Error 1: Forgetting Colon

python
if age >= 18  # SyntaxError: missing colon
    print("Adult")

if age >= 18:  # ✓
    print("Adult")

Error 2: Indentation Error

python
# ✗ Inconsistent indentation
if age >= 18:
    print("Adult")
  print("Can vote")  # IndentationError

# ✓ Consistent indentation
if age >= 18:
    print("Adult")
    print("Can vote")

Error 3: Using Assignment Instead of Comparison

python
age = 18
if age = 18:  # ✗ SyntaxError: should use ==
    print("Exactly 18")

if age == 18:  # ✓
    print("Exactly 18")

Error 4: Empty if Block

python
if age >= 18:
    # ✗ SyntaxError: cannot be empty

if age >= 18:
    pass  # ✓ Use pass as placeholder

Complete Practical Example: Survey Data Processing

python
# === Survey data ===
respondent_id = 1001
age = 35
gender = "Female"
education = "Master's Degree"
employment_status = "Employed"
annual_income = 85000
marital_status = "Married"
num_children = 2

# === Data validation and classification ===

print(f"=== Respondent {respondent_id} Data Report ===\n")

# 1. Age group
if age < 25:
    age_group = "Youth (<25)"
elif age < 45:
    age_group = "Young adult (25-44)"
elif age < 65:
    age_group = "Middle-aged (45-64)"
else:
    age_group = "Senior (65+)"

print(f"Age group: {age_group}")

# 2. Education level coding
education_levels = {
    "High School": 1,
    "Associate Degree": 2,
    "Bachelor's Degree": 3,
    "Master's Degree": 4,
    "Doctoral Degree": 5
}

if education in education_levels:
    education_code = education_levels[education]
    if education_code >= 4:
        education_category = "Advanced degree"
    elif education_code >= 3:
        education_category = "Bachelor's"
    else:
        education_category = "Associate or below"
else:
    education_code = 0
    education_category = "Unknown"

print(f"Education level: {education} ({education_category})")

# 3. Income grouping
if annual_income < 30000:
    income_quartile = "Q1 (Low income)"
elif annual_income < 60000:
    income_quartile = "Q2 (Lower-middle income)"
elif annual_income < 100000:
    income_quartile = "Q3 (Upper-middle income)"
else:
    income_quartile = "Q4 (High income)"

print(f"Income group: ${annual_income:,} ({income_quartile})")

# 4. Family structure
if marital_status == "Married" and num_children > 0:
    family_type = "Married with children"
elif marital_status == "Married":
    family_type = "Married without children"
elif num_children > 0:
    family_type = "Single parent"
else:
    family_type = "Single"

print(f"Family structure: {family_type}")

# 5. Target demographic determination (example: highly educated high-income young adults)
is_target_demographic = (
    (age_group == "Young adult (25-44)") and
    (education_category == "Advanced degree") and
    (income_quartile in ["Q3 (Upper-middle income)", "Q4 (High income)"])
)

if is_target_demographic:
    print("\n✓ Matches target demographic profile")
else:
    print("\n✗ Does not match target demographic profile")

Practice Exercises

Exercise 1: Tax Rate Calculation

python
# Calculate tax based on income
income = 75000

# Tax table:
# 0-50000: 10%
# 50001-100000: 20%
# 100001+: 30%

# Calculate tax owed and output

Exercise 2: Student Scholarship Evaluation

python
gpa = 3.8
volunteer_hours = 50
research_papers = 2

# Scholarship rules:
# - First-tier: GPA >= 3.8 and (volunteer hours >= 40 or papers >= 2)
# - Second-tier: GPA >= 3.5
# - Third-tier: GPA >= 3.0
# - No scholarship: Other cases

# Determine scholarship tier

Exercise 3: Health Risk Assessment

python
age = 55
bmi = 28
smoking = True
exercise_days_per_week = 1
family_history = True  # Family medical history

# Risk scoring rules:
# - Age > 50: +2 points
# - BMI >= 25: +2 points
# - Smoking: +3 points
# - Exercise days < 3: +1 point
# - Family history: +2 points

# Calculate total score and give risk level:
# 0-2: Low risk
# 3-5: Medium risk
# 6+: High risk

Next Steps

In the next section, we'll learn about loops (for/while), enabling programs to perform repetitive tasks.

Keep going!

Released under the MIT License. Content © Author.