Conditional Statements — If and Else | Python for Analysis Tutorial - Learn with VOKS
Back Next

Conditional Statements — If and Else


In data analysis, your code needs the ability to make decisions. You don’t always want to perform the same operation on every row of data. For example, you might want to flag "High Value" customers only if their spending exceeds a certain threshold, or categorize a temperature as "Freezing" only if it is below zero.

Conditional Statements allow your Python script to execute specific blocks of code only when certain conditions are met.


1. The Structure of an if Statement

The if statement is the most basic form of decision-making. It evaluates a condition to see if it is True or False.

  • Syntax: You write the keyword if, followed by a condition, and a colon (:).
  • The Code Block: The code you want to run must be indented.

Python


# A simple check for sales targets
sales = 1200
target = 1000

if sales > target:
    print("Target Achieved!")

Why the Colon and Indentation matter: The colon tells Python that a "choice" is coming up. The indentation tells Python exactly which lines of code belong to that choice. If you forget to indent, Python will throw an error.


2. The else Statement: The Alternative

The if statement handles what happens when a condition is True. The else statement handles every other case (when the condition is False).

Think of it as a fork in the road. You can only take one path.

Python


age = 16

if age >= 18:
    print("Eligible to vote.")
else:
    print("Not eligible to vote.")


3. The elif (Else If) Statement: Multiple Choices

In real-world data, situations aren't always binary (Black or White). Often, you have multiple categories to check. elif allows you to check several conditions in order. Python will run the code for the first True condition it finds and skip the rest.

Example: Categorizing Customer Spending

Python


spend = 450

if spend >= 500:
    category = "Platinum"
elif spend >= 200:
    category = "Gold"
elif spend >= 50:
    category = "Silver"
else:
    category = "Bronze"

print("Customer Tier: " + category)

The Logic Flow: Python checks the if first. If that’s False, it moves to the first elif. If that’s False, it moves to the next. If all are False, it defaults to the else.


4. Nesting Conditionals

You can place an if statement inside another if statement. This is called Nesting. This is useful for "Deep Filtering"—for example, checking if a student passed an exam, and then checking if they passed with honors.

Python


score = 85
attendance = 92

if score >= 50:
    if attendance >= 90:
        print("Passed with perfect attendance bonus.")
    else:
        print("Passed.")
else:
    print("Failed.")
Pro-Tip for Data Analysts: While nesting is powerful, too much of it makes code hard to read (this is often called "Spaghetti Code"). Whenever possible, try to use Logical Operators (and, or) to simplify your conditions.


5. Using Logical Operators with if

To make your data analysis more efficient, you can combine conditions in a single line:

  • Using and: Both conditions must be True.
  • if stock < 10 and demand == "High": -> Order more stock.
  • Using or: At least one condition must be True.
  • if day == "Saturday" or day == "Sunday": -> Apply weekend pricing.


6. The "Short Hand" (Ternary Operator)

Sometimes, you want to assign a value to a variable based on a condition in a single line. This is great for keeping your data cleaning scripts concise.

Syntax: value_if_true if condition else value_if_false

Python


status = "Alert" if temperature > 100 else "Normal"


Python for Analysis
What is Python? Python Syntax, Comments, and Variables Python Data Types — Numeric, Strings, and Sequences Mapping Data Types — The Power of Dictionaries The Boolean Data Type — The Logic of Data Analysis Numbers and Type Casting Conditional Statements — If and Else Python Modules — Organizing and Reusing Code Number Arrays (NumPy) — The Foundation of Data Analysis Pandas; Pandas series, Dataframe, Read CSV, cleaning data, dealing with empty data, removing duplicates, pandas plotting Mastering Pandas for Data Analysis Data Visualization with Matplotlib Statistical Data Visualization
All Courses
Advance AI Bootstrap C C++ Computer Vision Content Writing CSS Cyber Security Data Analysis Deep Learning Email Marketing Excel Figma HTML Java Script Machine Learning MySQLi Node JS PHP Power Bi Python Python for AI Python for Analysis React React Native SEO SMM SQL