Conditional Statements — If and Else | Python for Analysis Tutorial - Learn with VOKS
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
Back Next

Conditional Statements — If and Else

Learn this topic step-by-step with VOKS Tutorials.

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"


QUICK KNOWLEDGE CHECK

Test Your Understanding

Answer 5 questions generated from this lesson. Your result is calculated instantly and is not saved.

0 / 5 answered
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
Course contents
Python for Analysis
01 What is Python? 02 Python Syntax, Comments, and Variables 03 Python Data Types — Numeric, Strings, and Sequences 04 Mapping Data Types — The Power of Dictionaries 05 The Boolean Data Type — The Logic of Data Analysis 06 Numbers and Type Casting 07 Conditional Statements — If and Else 08 Python Modules — Organizing and Reusing Code 09 Number Arrays (NumPy) — The Foundation of Data Analysis 10 Pandas; Pandas series, Dataframe, Read CSV, cleaning data, dealing with empty data, removing duplicates, pandas plotting 11 Mastering Pandas for Data Analysis 12 Data Visualization with Matplotlib 13 Statistical Data Visualization