📝 Python

elif in Python: Handling Multiple Branches 🎛️

0
Author
04e5cc8b-58ac-4bdc-bdee-661bbb
📅
Published
30.03.2026
⏱️
Reading time
4 min
👁️
Views
104
🌱
Level
Beginner

When if-else isn’t enough — use elif! Check multiple conditions in sequence.

🤔 The Problem with if-else

Imagine you need to check several cases:

# ❌ Bad — deeply nested ifs
score = 85

if score >= 90:
    print('Excellent!')
else:
    if score >= 80:
        print('Good!')
    else:
        if score >= 70:
            print('Satisfactory')
        else:
            print('Poor')

Hard to read! Too much nesting!

✨ The Solution: elif

elif = “else if”

# ✅ Good — easy to read
score = 85

if score >= 90:
    print('Excellent!')
elif score >= 80:
    print('Good!')
elif score >= 70:
    print('Satisfactory')
else:
    print('Poor')

How it works:
1. Checks the first condition (score >= 90) — False
2. Checks the second condition (score >= 80) — True!
3. Executes the code for the second condition
4. Stops (the remaining branches are skipped)

📐 Structure

if condition1:
    # Runs if condition1 is True
elif condition2:
    # Runs if condition1 is False and condition2 is True
elif condition3:
    # Runs if 1 and 2 are False and condition3 is True
else:
    # Runs if all are False

Key points:
- Conditions are evaluated top to bottom
- Only ONE block executes
- else is optional

🎯 Usage Examples

Example 1: Grades

print('📝 Grading System\n')

points = int(input('Points scored: '))

if points >= 90:
    grade = 'A'
elif points >= 80:
    grade = 'B'
elif points >= 70:
    grade = 'C'
elif points >= 60:
    grade = 'D'
else:
    grade = 'F'

print(f'Your grade: {grade}')

Example 2: Calculator

print('🧮 Calculator\n')

a = float(input('First number: '))
b = float(input('Second number: '))
operation = input('Operation (+, -, *, /): ')

if operation == '+':
    result = a + b
elif operation == '-':
    result = a - b
elif operation == '*':
    result = a * b
elif operation == '/':
    if b != 0:
        result = a / b
    else:
        result = 'Error: division by zero'
else:
    result = 'Unknown operation'

print(f'\nResult: {result}')

Example 3: Time of Day

hour = int(input('Current hour (0-23): '))

if hour < 6:
    print('🌙 Night — time to sleep!')
elif hour < 12:
    print('🌅 Morning — good morning!')
elif hour < 18:
    print('☀️ Afternoon — good afternoon!')
elif hour < 22:
    print('🌆 Evening — good evening!')
else:
    print('🌙 Late night — time for bed!')

Example 4: BMI with Details

print('🧮 BMI Calculator\n')

weight = float(input('Weight (kg): '))
height = float(input('Height (m): '))

bmi = weight / (height ** 2)

print(f'\nYour BMI: {bmi:.1f}')

if bmi < 16:
    print('⚠️ Severe underweight')
    print('Please consult a doctor!')
elif bmi < 18.5:
    print('⚠️ Underweight')
    print('Consider gaining some weight')
elif bmi < 25:
    print('✅ Normal weight')
    print('Great! Keep it up!')
elif bmi < 30:
    print('⚠️ Overweight')
    print('Consider a healthier diet')
elif bmi < 35:
    print('⚠️ Obesity class I')
    print('You should lose weight')
elif bmi < 40:
    print('🚨 Obesity class II')
    print('Please see a doctor!')
else:
    print('🚨 Obesity class III')
    print('See a doctor urgently!')

Example 5: Rock-Paper-Scissors

import random

choices = {1: 'rock', 2: 'scissors', 3: 'paper'}

print('🎮 Rock-Paper-Scissors\n')
print('1 - Rock')
print('2 - Scissors')
print('3 - Paper\n')

player = int(input('Your choice: '))
computer = random.randint(1, 3)

print(f'\nYou: {choices[player]}')
print(f'Computer: {choices[computer]}\n')

if player == computer:
    print('🤝 Draw!')
elif (player == 1 and computer == 2) or \
     (player == 2 and computer == 3) or \
     (player == 3 and computer == 1):
    print('🎉 You win!')
else:
    print('😢 Computer wins!')

⚡ Common Mistakes

Mistake 1: Wrong Order

# ❌ Bad — first condition swallows everything else
age = 15

if age >= 0:
    print('Age is positive')
elif age >= 13:
    print('Teenager')  # Never executes!
elif age >= 18:
    print('Adult')     # Never executes!

# ✅ Good — from most specific to most general
if age >= 18:
    print('Adult')
elif age >= 13:
    print('Teenager')
elif age >= 0:
    print('Age is positive')

Mistake 2: Forgot the Colon

# ❌ Error
if age > 18:
    print('Over 18')
elif age > 13  # SyntaxError!
    print('Teenager')

# ✅ Correct
if age > 18:
    print('Over 18')
elif age > 13:
    print('Teenager')

Mistake 3: Inconsistent Indentation

# ❌ Error
if age > 18:
    print('Over 18')
  elif age > 13:  # Wrong indentation!
    print('Teenager')

# ✅ Correct — all at the same level
if age > 18:
    print('Over 18')
elif age > 13:
    print('Teenager')

🎨 Style and Readability

Bad

if x>10 and y<5 or z==0:print('test');result=x*2

Good

if (x > 10 and y < 5) or z == 0:
    print('test')
    result = x * 2

Tips:

  • Spaces around operators: x > 10 not x>10
  • Parentheses for complex conditions: (a and b) or c
  • Each block on its own line
  • Descriptive variable names

🔄 elif vs Separate ifs

With elif (only ONE block executes)

score = 85

if score >= 90:
    print('A')
elif score >= 80:
    print('B')  # THIS executes
elif score >= 70:
    print('C')  # This is skipped

With separate ifs (ALL matching blocks can execute!)

score = 85

if score >= 90:
    print('A')
if score >= 80:
    print('B')  # Executes
if score >= 70:
    print('C')  # This executes too!

📋 Cheat Sheet

# Structure
if condition1:
    code1
elif condition2:
    code2
elif condition3:
    code3
else:
    default_code

# Rules:
# 1. Evaluated top to bottom
# 2. Only ONE block executes
# 3. Execution stops after the first match
# 4. else is optional
# 5. You can have as many elif branches as you need

# Order matters!
# From most specific to most general

🎓 Summary

  • elif = “else if”
  • Use it when you need to check multiple cases
  • More readable than nested ifs
  • Only ONE block executes (the first one that is True)
  • The order of conditions MATTERS!
  • Evaluate from most specific to most general

elif makes code clear when there are many branches! 💪

Your reaction to the article

💬 Comments (0)

🔐 Sign in to leave a comment
🚪 Login
💭

No comments yet

Be the first to share your opinion about this article!

🔗 Similar

Similar articles

Continue learning with these materials

📝

Setting Up Your Environment: Python, pip, and VS …

Before writing code locally, you need to set up three tools: Python, pip, and VS...

📅 04.06.2026 👁️ 16
📝

The datetime Module: Working with Dates and Times

datetime is Python's standard module for working with dates and times. It's part of the...

📅 08.05.2026 👁️ 66
📝

.env Files and Environment Variables: Keeping Sec…

Imagine you wrote a program with an API key hardcoded in the source and pushed...

📅 08.05.2026 👁️ 75

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!