TutorialsPythonConditionals — if, elif, else

Conditionals — if, elif, else

Write if/elif/else logic to categorise, flag and filter data in Python

Conditionals let your code make decisions — "if sales > 50000, mark as High; elif sales > 20000, mark as Medium; else mark as Low." In data analysis, this is how you create category columns, flag anomalies, and apply business rules to data. Python uses indentation (4 spaces) instead of brackets to define code blocks. This is unlike most other languages and is the #1 syntax mistake beginners make.

Examples

if / elif / else
sales = 45000

# Basic
if sales > 50000:
    category = "High"
elif sales > 20000:
    category = "Medium"
else:
    category = "Low"

print(category)   # "Medium"

# Compound conditions
region = "Delhi"
quarter = "Q4"

if region == "Delhi" and quarter == "Q4":
    bonus = 0.15
elif region == "Delhi" or sales > 100000:
    bonus = 0.10
else:
    bonus = 0.05

# One-liner (ternary)
label = "High" if sales > 50000 else "Low"

# With not
if not (sales == 0):
    margin = profit / sales
💡 Indentation matters — Python uses 4 spaces (not tabs) to define code blocks. Wrong indentation causes IndentationError.
Applying logic to data with Pandas
import pandas as pd

df = pd.DataFrame({"Sales": [45000, 18000, 72000, 9000, 55000]})

# Apply category logic to a column
def categorise(s):
    if s > 50000:
        return "High"
    elif s > 20000:
        return "Medium"
    else:
        return "Low"

df["Category"] = df["Sales"].apply(categorise)

# Cleaner with np.select (for multiple conditions):
import numpy as np
conditions = [df["Sales"] > 50000, df["Sales"] > 20000]
choices    = ["High", "Medium"]
df["Category"] = np.select(conditions, choices, default="Low")

# Even cleaner with pd.cut (for range bins):
df["Band"] = pd.cut(df["Sales"],
                    bins=[0, 20000, 50000, float("inf")],
                    labels=["Low", "Medium", "High"])

Key Points

  • Indentation (4 spaces) defines code blocks — this is Python syntax, not style
  • and / or / not — Python uses words, not && || ! like other languages
  • For applying logic to DataFrame columns, use .apply() or np.select()
  • pd.cut() is the easiest way to bin numeric data into labelled ranges
  • Comparison operators: == (equal), != (not equal), >, <, >=, <=

Practice Question

What is the output of: label = "Pass" if 85 >= 60 else "Fail"?

Related Topics

Loops — for and whileIterate over data, automate repetitive tasks, and process multiple files with loopsFunctions in PythonWrite reusable functions to avoid repeating logic across your analysis scriptsFeature Engineering for AnalystsCreate new meaningful columns from existing data to improve analysis and modelling