Python Foundation

Conditional Statements in Python

01 · Introduction Conditional Statements · 1 of 13

What are Conditional Statements?

In real life we make decisions every day.

  • If it is raining → take an umbrella
  • If the red light is on → stop the vehicle
  • If marks are 40 or more → pass, otherwise fail

In programming also we need the same decision-making power. Conditional statements give this power to Python.

A conditional statement checks a condition (something that is either True or False). Based on the result, it decides which block of code should run.

Python has three main keywords for this:

  • if → check a condition
  • elif → check another condition if previous ones failed
  • else → run when all conditions are False

These three keywords are the foundation of decision making in Python. Almost every program you write (especially in data analysis) will use them.

02 · if Statement Conditional Statements · 2 of 13

The if Statement

The simplest form of decision making is the if statement.

Syntax:

Python
if condition:
    # this block runs only when condition is True
    statement 1
    statement 2

Important points:

  • The condition must end with a colon :
  • The code inside the if block must be indented (usually 4 spaces)
  • If the condition is True, the indented block runs
  • If the condition is False, the indented block is completely skipped

Example 1 – Simple if

Python
age = 20

if age >= 18:
    print("You are an adult")
    print("You can vote")
Here age is 20, so the condition age >= 18 becomes True. Both print statements will execute. If age was 15, nothing would be printed.

Example 2 – Condition is False

Python
marks = 32

if marks >= 40:
    print("Pass")
    print("Congratulations")

print("This line always runs")
marks is 32, so the condition is False. The two print statements inside the if block are skipped. Only the last print statement runs because it is outside the if block.
03 · if-else Statement Conditional Statements · 3 of 13

The if-else Statement

Many times we want to do one thing if the condition is True, and something else if the condition is False. For this we use if-else.

Syntax:

Python
if condition:
    # runs when condition is True
    statement A
else:
    # runs when condition is False
    statement B

Example 1 – Pass or Fail

Python
marks = 38

if marks >= 40:
    print("Result: Pass")
else:
    print("Result: Fail")
    print("Please try again")
Because marks is 38 (less than 40), the else block runs. Output will be:
Result: Fail
Please try again

Example 2 – Even or Odd

Python
number = 17

if number % 2 == 0:
    print(number, "is Even")
else:
    print(number, "is Odd")
% is the modulus operator (gives remainder). 17 divided by 2 leaves remainder 1, so the condition is False and else block runs.
04 · if-elif-else Conditional Statements · 4 of 13

The if-elif-else Ladder

When you have more than two possible decisions, you use elif (short form of else-if).

Syntax:

Python
if condition1:
    # runs if condition1 is True
elif condition2:
    # runs if condition1 is False and condition2 is True
elif condition3:
    # runs if previous conditions are False and condition3 is True
else:
    # runs only when all above conditions are False

Important rules:

  • Python checks conditions from top to bottom
  • As soon as one condition becomes True, that block runs and the rest are skipped
  • You can have as many elif as you want
  • else is optional but recommended

Example – Grade System

Python
marks = 78

if marks >= 90:
    print("Grade: A+")
elif marks >= 80:
    print("Grade: A")
elif marks >= 70:
    print("Grade: B")
elif marks >= 60:
    print("Grade: C")
elif marks >= 40:
    print("Grade: D")
else:
    print("Grade: F (Fail)")
marks = 78
First condition ( >= 90) → False
Second condition ( >= 80) → False
Third condition ( >= 70) → True → prints "Grade: B" and stops checking further.

Example – Age Category

Python
age = 15

if age < 13:
    print("Child")
elif age < 20:
    print("Teenager")
elif age < 60:
    print("Adult")
else:
    print("Senior Citizen")
05 · Comparison Operators Conditional Statements · 5 of 13

Comparison Operators used in Conditions

These operators are used to compare two values. The result is always either True or False.

Python
x = 10
y = 25

print(x == y)    # Equal to                  → False
print(x != y)    # Not equal to              → True
print(x > y)     # Greater than              → False
print(x < y)     # Less than                 → True
print(x >= y)    # Greater than or equal to  → False
print(x <= y)    # Less than or equal to     → True

Common mistakes:

  • Using = instead of == (single = is assignment, double == is comparison)
  • Writing => instead of >=
06 · Logical Operators Conditional Statements · 6 of 13

Logical Operators (and, or, not)

Sometimes one condition is not enough. We need to combine multiple conditions.

1. and → True only when all conditions are True

Python
age = 25
salary = 40000

if age >= 18 and salary >= 30000:
    print("Eligible for loan")
else:
    print("Not eligible")

2. or → True when at least one condition is True

Python
day = "Sunday"

if day == "Saturday" or day == "Sunday":
    print("Weekend")
else:
    print("Working day")

3. not → reverses the result

Python
is_raining = False

if not is_raining:
    print("You can go outside")
else:
    print("Take an umbrella")
07 · Truthy & Falsy Values Conditional Statements · 7 of 13

Truthy and Falsy Values in Python

In Python, many values are automatically treated as False in conditions. These are called Falsy values.

Falsy values:

  • False
  • None
  • 0 (zero)
  • "" (empty string)
  • [] (empty list)
  • () (empty tuple)
  • {} (empty dictionary)
  • set() (empty set)

Everything else is considered Truthy.

Python
name = ""

if name:
    print("Hello", name)
else:
    print("Name is empty")

marks = 0
if marks:
    print("Marks available")
else:
    print("Marks is zero")
08 · With Lists Conditional Statements · 8 of 13

Using Conditions with Lists

Lists are one of the most common data types used with conditions.

1. Check if an element exists

Python
fruits = ["apple", "banana", "mango", "orange"]

if "mango" in fruits:
    print("Mango is available")
else:
    print("Mango is not available")

2. Check the length of list

Python
students = ["Rahul", "Priya", "Amit"]

if len(students) > 0:
    print("There are", len(students), "students")
else:
    print("List is empty")

3. Check value at a specific position

Python
marks = [56, 78, 92, 45]

if marks[2] >= 90:
    print("Third student got excellent marks")
else:
    print("Third student marks are normal")

4. Check if list is empty using truthy/falsy

Python
cart = []

if cart:
    print("Cart has items")
else:
    print("Cart is empty")
09 · With Tuples Conditional Statements · 9 of 13

Using Conditions with Tuples

Tuples work almost the same way as lists in conditions because both are sequences.

Python
point = (10, 20, 30)

# Check length
if len(point) == 3:
    print("This is a 3D point")

# Check membership
if 20 in point:
    print("Y-coordinate is 20")

# Check specific index
if point[0] > 0:
    print("X is positive")

Example with tuple of student data

Python
student = ("Kundan", 22, "Data Analytics")

name, age, course = student

if age >= 18 and course == "Data Analytics":
    print(name, "is eligible for advanced batch")
else:
    print(name, "is not eligible")
10 · With Sets Conditional Statements · 10 of 13

Using Conditions with Sets

Sets are very powerful when you want to check membership or compare groups of items.

Python
required_skills = {"python", "sql", "excel"}
candidate_skills = {"python", "sql", "powerbi", "excel"}

# Check if candidate has a particular skill
if "python" in candidate_skills:
    print("Has Python skill")

# Check if candidate has ALL required skills
if required_skills.issubset(candidate_skills):
    print("Candidate has all required skills")
else:
    print("Some skills are missing")

# Check common skills
common = required_skills.intersection(candidate_skills)
if len(common) >= 2:
    print("Has at least 2 matching skills")
11 · With Dictionaries Conditional Statements · 11 of 13

Using Conditions with Dictionaries

Dictionaries are extremely common in real projects. Most of the time we check keys and values.

1. Check if a key exists

Python
student = {
    "name": "Kundan",
    "age": 22,
    "course": "Data Analytics",
    "marks": 87
}

if "marks" in student:
    print("Marks are available:", student["marks"])
else:
    print("Marks key not found")

2. Safe way using .get()

Python
# .get() returns None (or default) if key is missing
if student.get("attendance") is None:
    print("Attendance not recorded")
else:
    print("Attendance:", student["attendance"])

3. Multiple conditions on dictionary values

Python
if student["age"] >= 18 and student["marks"] >= 80:
    print(student["name"], "→ Excellent and eligible")
elif student["marks"] >= 60:
    print(student["name"], "→ Good performance")
else:
    print(student["name"], "→ Needs improvement")
12 · Nested Conditions Conditional Statements · 12 of 13

Nested if Statements

You can put one if inside another if. This is called nesting.

Python
student = {
    "name": "Priya",
    "marks": 92,
    "attendance": 88
}

if student["marks"] >= 80:
    print("Marks are good")
    
    if student["attendance"] >= 75:
        print("Attendance is also good")
        print(student["name"], "is eligible for certificate")
    else:
        print("Marks good but attendance is low")
        print("Not eligible for certificate")
else:
    print("Marks are not sufficient")
First Python checks marks. Only if marks are >= 80, it enters the inner if and checks attendance. This is how we build complex decision logic step by step.
13 · Real Business Example Conditional Statements · 13 of 13

Bank Customer Eligibility Check

This is a realistic example that combines most of the concepts we learned.

Python
customer = {
    "name": "Amit Sharma",
    "age": 34,
    "balance": 85000,
    "job": "management",
    "housing_loan": False,
    "personal_loan": False,
    "previous_campaign": "success"
}

print("Customer:", customer["name"])
print("-" * 40)

# Step 1: Basic filters
if customer["age"] < 25 or customer["age"] > 60:
    print("Rejected → Age not in range 25-60")

elif customer["balance"] < 50000:
    print("Rejected → Balance less than 50000")

elif customer["housing_loan"] or customer["personal_loan"]:
    print("Rejected → Customer already has a loan")

# Step 2: Preferred job check
elif customer["job"] not in ["management", "technician", "admin"]:
    print("Rejected → Job type not preferred")

# Step 3: Previous campaign result
elif customer["previous_campaign"] != "success":
    print("Rejected → Previous campaign was not successful")

# Step 4: All conditions passed
else:
    print("SELECTED → Eligible for Premium Campaign")
    print("Action: Call the customer this week")
This example shows how real business rules are converted into if-elif-else logic. You will use similar patterns many times when working with customer data, bank data, or any filtered reports.
Home Conditional Statements

Conditional Statements in Python

Complete and detailed explanation of if, elif, else with all data types.

Select any topic from the left sidebar to begin.


Start Learning →