TutorialsPythonIf / Elif / Else — Conditional Logic

If / Elif / Else — Conditional Logic

Write conditional logic to classify, flag, and filter data in Python

Conditional statements let your code make decisions based on data values. In data analysis, you use conditionals constantly — to classify customers into tiers, flag outliers, assign labels, and apply business rules. Python uses if / elif / else. Indentation (4 spaces) defines the code block — there are no curly braces like in other languages.

Syntax

if condition:
    # runs if condition is True
elif another_condition:
    # runs if first is False but this is True
else:
    # runs if all conditions are False

Examples

Classify data with conditionals
salary = 72000

# Basic if-else
if salary >= 100000:
    tier = "Senior"
elif salary >= 60000:
    tier = "Mid"
elif salary >= 35000:
    tier = "Junior"
else:
    tier = "Entry"

print(tier)  # "Mid"

# Multiple conditions with and / or
city = "Noida"
experience = 3

if city in ["Noida", "Gurgaon", "Delhi"] and experience >= 2:
    print("Strong NCR candidate")
else:
    print("Needs review")
Apply conditionals in pandas with np.where and apply()
import pandas as pd
import numpy as np

df = pd.DataFrame({
    "Name": ["Rahul", "Priya", "Arun"],
    "Salary": [45000, 78000, 32000]
})

# One condition: np.where (fast)
df["Tier"] = np.where(df["Salary"] >= 60000, "Senior", "Junior")

# Multiple conditions: np.select
conditions = [
    df["Salary"] >= 100000,
    df["Salary"] >= 60000,
    df["Salary"] >= 35000
]
choices = ["Senior", "Mid", "Junior"]
df["Tier2"] = np.select(conditions, choices, default="Entry")

# Complex logic: apply() with a function
def classify(row):
    if row["Salary"] >= 60000:
        return "Mid+"
    return "Below Mid"

df["Class"] = df.apply(classify, axis=1)
💡 In pandas: use np.where for one condition, np.select for multiple — they are much faster than apply() on large DataFrames.

Key Points

  • Python uses indentation (4 spaces) for code blocks — not curly braces
  • elif = "else if" — check multiple conditions in order
  • Comparison operators: == != > < >= <=
  • Logical operators: and, or, not (Python uses words, not && ||)
  • In pandas: np.where > np.select > apply() — in order of performance

Practice Question

Which operator checks if two values are equal in Python?