PYTHON IF ELSE & ELIF

Control the flow of your Python programs by making decisions based on conditions, comparisons, and real-world business rules.

🔀 What are If, Else and Elif in Python?

Python if, elif, and else statements allow a program to make decisions. Python evaluates a condition and executes the appropriate block of code. This is commonly used in login systems, shopping applications, banking systems, payroll software, education platforms, and many other real-world applications.

1. If, Elif and Else

if

Checks the first condition. If it is True, the associated code is executed.

Python
if age >= 18:
    print("Adult")

elif

Means "else if". It allows the program to test another condition.

Python
elif age >= 13:
    print("Teenager")

else

Executes when none of the previous conditions are True.

Python
else:
    print("Child")
2. Basic If-Elif-Else Syntax
The following structure is used when a program needs to select one result from several possible conditions.
Syntax
if condition1:
    # code for condition1

elif condition2:
    # code for condition2

else:
    # default code
Important: Python uses indentation to identify which statements belong to the if, elif, or else block. Four spaces are normally used for indentation.
3. How If-Elif-Else Works
Start Program
↓
Check if condition
↓
TRUE → Execute IF block
FALSE → Check ELIF condition
↓
TRUE → Execute ELIF block
FALSE → Execute ELSE block
4. Simple Example – Age Check
A registration system can classify a user into different age groups.
Age Classification
age = 25

if age >= 18:
    print("Adult")

elif age >= 13:
    print("Teenager")

else:
    print("Child")
Output: Adult
5. Real-Time Example – Login System
A login application can check the username, password, and account status before allowing the user to continue.
Login Validation
username = "admin"
password = "python123"
account_active = True

if username == "admin" and password == "python123":

    if account_active:
        print("Login successful")

    else:
        print("Account is inactive")

else:
    print("Invalid username or password")
Output: Login successful
Real-world use: Similar decision logic can be used in employee portals, e-commerce websites, learning systems, and administrative applications.
6. Real-Time Example – Shopping Discount
An e-commerce website can calculate a discount according to the customer's order amount.
E-Commerce Discount
order_amount = 7500

if order_amount >= 10000:
    discount = 20

elif order_amount >= 5000:
    discount = 10

elif order_amount >= 2000:
    discount = 5

else:
    discount = 0

discount_amount = order_amount * discount / 100
final_amount = order_amount - discount_amount

print("Discount:", discount, "%")
print("Final Amount:", final_amount)
Output: Discount: 10 % Final Amount: 6750.0
Business Rule: Python checks the conditions from top to bottom. Once one condition is True, the remaining elif and else blocks are skipped.
7. Real-Time Example – ATM Withdrawal
An ATM can validate the withdrawal amount before processing a transaction.
ATM Transaction
balance = 25000
withdraw_amount = 8000

if withdraw_amount <= 0:
    print("Invalid withdrawal amount")

elif withdraw_amount > balance:
    print("Insufficient balance")

elif withdraw_amount % 100 != 0:
    print("Amount must be a multiple of 100")

else:
    balance = balance - withdraw_amount

    print("Withdrawal successful")
    print("Remaining balance:", balance)
Output: Withdrawal successful Remaining balance: 17000
8. Real-Time Example – Employee Performance Bonus
A payroll system can determine the bonus percentage based on an employee's performance rating.
Payroll Example
rating = 4.5
salary = 60000

if rating >= 4.5:
    bonus_percent = 20

elif rating >= 4.0:
    bonus_percent = 15

elif rating >= 3.0:
    bonus_percent = 10

else:
    bonus_percent = 5

bonus = salary * bonus_percent / 100

print("Bonus Percentage:", bonus_percent)
print("Bonus Amount:", bonus)
Output: Bonus Percentage: 20 Bonus Amount: 12000.0
9. Real-Time Example – Student Grade
An education application can calculate a grade from a student's percentage.
Grade Calculation
percentage = 82

if percentage >= 90:
    grade = "A+"

elif percentage >= 80:
    grade = "A"

elif percentage >= 70:
    grade = "B"

elif percentage >= 60:
    grade = "C"

elif percentage >= 50:
    grade = "D"

else:
    grade = "Fail"

print("Percentage:", percentage)
print("Grade:", grade)
Output: Percentage: 82 Grade: A
10. Real-Time Example – Delivery Charges
An online shopping application can calculate delivery charges according to the order total.
Delivery Charge
order_total = 850

if order_total >= 1000:
    delivery_charge = 0

elif order_total >= 500:
    delivery_charge = 40

else:
    delivery_charge = 70

print("Delivery Charge:", delivery_charge)
Output: Delivery Charge: 40
11. Real-Time Example – Weather Recommendation
A weather application can display different recommendations depending on the temperature.
Weather Logic
temperature = 34

if temperature >= 40:
    message = "Extreme heat - stay indoors"

elif temperature >= 30:
    message = "Hot weather - stay hydrated"

elif temperature >= 20:
    message = "Pleasant weather"

else:
    message = "Cool weather - carry a jacket"

print(message)
Output: Hot weather - stay hydrated
12. Nested If – Driving Eligibility
A nested if is an if statement placed inside another if statement. It is useful when a decision depends on multiple levels of validation.
Driving Eligibility
age = 25
has_license = True

if age >= 18:

    if has_license:
        print("You can drive")

    else:
        print("You need a driving license")

else:
    print("You are not eligible to drive")
Output: You can drive
13. Using AND / OR with If

Using AND

All conditions connected with and must be True.

AND Example
age = 25
salary = 50000

if age >= 21 and salary >= 30000:
    print("Eligible for the offer")
else:
    print("Not eligible")
Eligible for the offer

Using OR

At least one condition connected with or must be True.

OR Example
is_admin = False
is_manager = True

if is_admin or is_manager:
    print("Access granted")
else:
    print("Access denied")
Access granted
14. If vs Elif vs Else

if

Used to test the first condition. It starts the decision-making block.

if
if score >= 90:
    print("Excellent")

elif

Checks another condition when the previous condition was False.

elif
elif score >= 60:
    print("Passed")

else

Handles the default case when all previous conditions are False.

else
else:
    print("Failed")
15. Common Mistakes

Missing Colon

Correct Syntax
# Incorrect
if age >= 18
    print("Adult")

# Correct
if age >= 18:
    print("Adult")

Incorrect Indentation

Correct Indentation
# Incorrect
if age >= 18:
print("Adult")

# Correct
if age >= 18:
    print("Adult")
Remember: Python is indentation-sensitive. Keep the statements belonging to an if, elif, or else block consistently indented.
16. Best Practices

Keep Conditions Readable

Example
if age >= 18 and has_license:
    print("Eligible")

Order Conditions Carefully

Example
if score >= 90:
    grade = "A"

elif score >= 75:
    grade = "B"

elif score >= 60:
    grade = "C"

else:
    grade = "D"

Use Else as the Default Case

Example
if status == "active":
    print("User active")
else:
    print("User unavailable")

Avoid Unnecessary Nesting

Example
if age >= 18 and has_license:
    print("Can drive")

Key Takeaways

  • if checks the first condition.
  • elif checks additional conditions.
  • else handles the default case.
  • Only the first matching branch in an if/elif/else chain executes.
  • Python uses indentation to define code blocks.
  • Conditions can use comparison operators such as ==, !=, >, <, >= and <=.
  • and requires all combined conditions to be True.
  • or requires at least one combined condition to be True.
  • If/elif/else is widely used in login systems, shopping applications, banking, payroll, education, delivery, and many other real-world programs.