Table of Contents
Toggle
Python’s if-else statements let your program make decisions.
✅ if-else handles two conditions (true/false).
✅ if-elif-else is used when multiple conditions must be checked.
Think of it like a traffic light 🚦:
Green = Go, Red = Stop, Yellow = Prepare. Python uses these statements to guide program flow.
The if-else statement lets you run one block of code if the condition is True,
and another if the condition is False.
if condition:
# Code runs if True
else:
# Code runs if False
Check if someone is old enough to vote:
age = 25
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")
Use if-elif-else when you need to test more than two conditions.
Python checks each condition from top to bottom and executes the first one that’s True.
if condition1:
# Runs if condition1 is True
elif condition2:
# Runs if condition2 is True
else:
# Runs if no condition is True
Apply discount based on purchase amount:
amount = 2500
if amount > 10000:
discount = 20
elif amount > 5000:
discount = 10
elif amount > 1000:
discount = 5
else:
discount = 0
print("Final Payable Amount:", amount - (amount * discount / 100))
You can put one if inside another.
This is useful when a decision depends on two levels of conditions.
num = 15
if num > 0:
if num % 2 == 0:
print("Positive even number")
else:
print("Positive odd number")
✅ Use if-else for two-way decisions.
✅ Use if-elif-else for multiple conditions.
✅ Use nested if for layered decisions.
By mastering these, you can build programs that think logically and react differently based on inputs.
Next Up → Python Loops 🔁
