Conditional Statements in Python
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 conditionelif→ check another condition if previous ones failedelse→ 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.
The if Statement
The simplest form of decision making is the if statement.
Syntax:
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
ifblock 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
age = 20
if age >= 18:
print("You are an adult")
print("You can vote")
age >= 18 becomes True.
Both print statements will execute.
If age was 15, nothing would be printed.
Example 2 – Condition is False
marks = 32
if marks >= 40:
print("Pass")
print("Congratulations")
print("This line always runs")
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:
if condition:
# runs when condition is True
statement A
else:
# runs when condition is False
statement B
Example 1 – Pass or Fail
marks = 38
if marks >= 40:
print("Result: Pass")
else:
print("Result: Fail")
print("Please try again")
Result: Fail
Please try again
Example 2 – Even or Odd
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.
The if-elif-else Ladder
When you have more than two possible decisions, you use elif
(short form of else-if).
Syntax:
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
elifas you want elseis optional but recommended
Example – Grade System
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)")
First condition ( >= 90) → False
Second condition ( >= 80) → False
Third condition ( >= 70) → True → prints "Grade: B" and stops checking further.
Example – Age Category
age = 15
if age < 13:
print("Child")
elif age < 20:
print("Teenager")
elif age < 60:
print("Adult")
else:
print("Senior Citizen")
Comparison Operators used in Conditions
These operators are used to compare two values.
The result is always either True or False.
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>=
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
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
day = "Sunday"
if day == "Saturday" or day == "Sunday":
print("Weekend")
else:
print("Working day")
3. not → reverses the result
is_raining = False
if not is_raining:
print("You can go outside")
else:
print("Take an umbrella")
Truthy and Falsy Values in Python
In Python, many values are automatically treated as False in conditions. These are called Falsy values.
Falsy values:
FalseNone0(zero)""(empty string)[](empty list)()(empty tuple){}(empty dictionary)set()(empty set)
Everything else is considered Truthy.
name = ""
if name:
print("Hello", name)
else:
print("Name is empty")
marks = 0
if marks:
print("Marks available")
else:
print("Marks is zero")
Using Conditions with Lists
Lists are one of the most common data types used with conditions.
1. Check if an element exists
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
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
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
cart = []
if cart:
print("Cart has items")
else:
print("Cart is empty")
Using Conditions with Tuples
Tuples work almost the same way as lists in conditions because both are sequences.
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
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")
Using Conditions with Sets
Sets are very powerful when you want to check membership or compare groups of items.
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")
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
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()
# .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
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")
Nested if Statements
You can put one if inside another if.
This is called nesting.
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")
Bank Customer Eligibility Check
This is a realistic example that combines most of the concepts we learned.
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")
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 →
