Python Notes
Learn how to use elif (else if) in Python for multi-way decision making. Master chained conditions, grade calculators, menu systems, and real-world programs with Hindi explanations.
Introduction (परिचय)
elif = "else if" का short form।
जब हमें दो से अधिक conditions check करनी हों, तब elif का use करते हैं।
Real-Life Example: `` अगर (if) temperature > 40 → Very Hot 🥵 नहीं तो अगर (elif) temperature > 30 → Hot 😓 नहीं तो अगर (elif) temperature > 20 → Warm 😊 नहीं तो अगर (elif) temperature > 10 → Cool 🌤️ नहीं तो (else) → Cold 🥶 ``Flow Diagram (प्रवाह आरेख)
Basic Example (बुनियादी उदाहरण)
Example 1: Grade System (ग्रेड सिस्टम)
marks = int(input("Enter marks (0-100): "))
if marks >= 90:
grade = "A+"
remarks = "Excellent! शानदार!"
elif marks >= 80:
grade = "A"
remarks = "Very Good! बहुत अच्छा!"
elif marks >= 70:
grade = "B+"
remarks = "Good! अच्छा!"
elif marks >= 60:
grade = "B"
remarks = "Above Average! औसत से ऊपर!"
elif marks >= 50:
grade = "C"
remarks = "Average! औसत!"
elif marks >= 33:
grade = "D"
remarks = "Pass! उत्तीर्ण!"
else:
grade = "F"
remarks = "Fail! अनुत्तीर्ण!"
print(f"Grade: {grade}")
print(f"Remarks: {remarks}")Output (marks = 75):
Example 2: Temperature Description
temp = float(input("Enter temperature (°C): "))
if temp >= 45:
print("Extreme Heat Warning! 🔥")
print("अत्यधिक गर्मी की चेतावनी!")
elif temp >= 35:
print("Very Hot Day! 🥵")
print("बहुत गर्म दिन!")
elif temp >= 25:
print("Warm Weather ☀️")
print("गर्म मौसम")
elif temp >= 15:
print("Pleasant Weather 😊")
print("सुहावना मौसम")
elif temp >= 5:
print("Cool Weather 🌤️")
print("ठंडा मौसम")
else:
print("Very Cold! 🥶")
print("बहुत ठंड है!")Output (temp = 28):
Warm Weather ☀️ गर्म मौसम
Example 3: Day of Week (सप्ताह का दिन)
day = int(input("Enter day number (1-7): "))
if day == 1:
print("Monday — सोमवार")
elif day == 2:
print("Tuesday — मंगलवार")
elif day == 3:
print("Wednesday — बुधवार")
elif day == 4:
print("Thursday — गुरुवार")
elif day == 5:
print("Friday — शुक्रवार")
elif day == 6:
print("Saturday — शनिवार")
elif day == 7:
print("Sunday — रविवार")
else:
print("Invalid day! Enter 1-7")
print("गलत दिन! 1-7 के बीच डालें")Output (day = 5):
Friday — शुक्रवार
Practical Programs (व्यावहारिक कार्यक्रम)
Program 1: Calculator with Menu
print("=== Simple Calculator ===")
print("=== सरल कैलकुलेटर ===")
print("1. Addition (जोड़)")
print("2. Subtraction (घटाव)")
print("3. Multiplication (गुणा)")
print("4. Division (भाग)")
choice = int(input("\nEnter choice (1-4): "))
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
if choice == 1:
result = a + b
print(f"{a} + {b} = {result}")
elif choice == 2:
result = a - b
print(f"{a} - {b} = {result}")
elif choice == 3:
result = a * b
print(f"{a} × {b} = {result}")
elif choice == 4:
if b != 0:
result = a / b
print(f"{a} ÷ {b} = {result:.2f}")
else:
print("Error: Cannot divide by zero!")
print("त्रुटि: शून्य से विभाजन नहीं होता!")
else:
print("Invalid choice! कृपया 1-4 चुनें।")Output (choice=1, a=15, b=7):
Program 2: BMI Calculator (BMI कैलकुलेटर)
weight = float(input("Enter weight (kg): "))
height = float(input("Enter height (m): "))
bmi = weight / (height ** 2)
print(f"\nYour BMI: {bmi:.2f}")
if bmi < 18.5:
category = "Underweight"
advice = "अधिक पोषण युक्त भोजन खाएं।"
elif bmi < 25.0:
category = "Normal weight"
advice = "बहुत अच्छा! स्वस्थ रहें।"
elif bmi < 30.0:
category = "Overweight"
advice = "व्यायाम बढ़ाएं और diet control करें।"
else:
category = "Obese"
advice = "डॉक्टर से सलाह लें।"
print(f"Category: {category}")
print(f"Advice: {advice}")Output (weight=70, height=1.75):
| Your BMI | 22.86 |
| Category | Normal weight |
| Advice | बहुत अच्छा! स्वस्थ रहें। |
Program 3: Month Name Program
month = int(input("Enter month number (1-12): "))
if month == 1:
name = "January — जनवरी"
days = 31
elif month == 2:
name = "February — फरवरी"
days = 28 # (29 in leap year)
elif month == 3:
name = "March — मार्च"
days = 31
elif month == 4:
name = "April — अप्रैल"
days = 30
elif month == 5:
name = "May — मई"
days = 31
elif month == 6:
name = "June — जून"
days = 30
elif month == 7:
name = "July — जुलाई"
days = 31
elif month == 8:
name = "August — अगस्त"
days = 31
elif month == 9:
name = "September — सितंबर"
days = 30
elif month == 10:
name = "October — अक्टूबर"
days = 31
elif month == 11:
name = "November — नवंबर"
days = 30
elif month == 12:
name = "December — दिसंबर"
days = 31
else:
name = "Invalid"
days = 0
if days > 0:
print(f"Month: {name}")
print(f"Days: {days}")
else:
print("Invalid month! 1-12 के बीच डालें।")Output (month = 7):
Month: July — जुलाई Days: 31
Program 4: Traffic Light System (ट्रैफिक लाइट)
light = input("Enter traffic light color (red/yellow/green): ").lower()
if light == "red":
print("STOP! 🔴")
print("रुकें!")
elif light == "yellow":
print("GET READY! 🟡")
print("तैयार रहें!")
elif light == "green":
print("GO! 🟢")
print("जाएं!")
else:
print("Invalid color!")
print("गलत रंग! red/yellow/green डालें।")Output (light = "green"):
GO! 🟢 जाएं!
Program 5: Internet Speed Check
speed = float(input("Enter internet speed (Mbps): "))
if speed >= 100:
print("🚀 Ultra Fast — Streaming 4K, Gaming, All fine!")
print("अल्ट्रा फास्ट — सब कुछ बेझिझक करें!")
elif speed >= 50:
print("⚡ Very Fast — HD Streaming, Video calls perfect")
print("बहुत तेज़ — HD स्ट्रीमिंग और video calls बढ़िया")
elif speed >= 25:
print("✅ Fast — Good for most tasks")
print("तेज़ — अधिकांश कार्यों के लिए उपयुक्त")
elif speed >= 10:
print("🆗 Moderate — Basic browsing and SD streaming")
print("ठीक-ठाक — सामान्य browsing के लिए")
elif speed >= 1:
print("🐌 Slow — Basic browsing only")
print("धीमा — केवल सामान्य browsing")
else:
print("❌ No Connection or too slow!")
print("कोई connection नहीं या बहुत धीमा!")Output (speed = 55):
⚡ Very Fast — HD Streaming, Video calls perfect बहुत तेज़ — HD स्ट्रीमिंग और video calls बढ़िया
If vs elif — Key Difference (महत्वपूर्ण अंतर)
marks = 85
# Using multiple if (WRONG approach)
print("--- Using multiple if ---")
if marks >= 33:
print("Pass") # prints
if marks >= 60:
print("Good") # prints
if marks >= 75:
print("Very Good") # prints
if marks >= 90:
print("Excellent") # does NOT print
# Problem: multiple blocks execute!
print("\n--- Using elif (CORRECT) ---")
# Using elif (CORRECT)
if marks >= 90:
print("Excellent")
elif marks >= 75:
print("Very Good") # Only this prints
elif marks >= 60:
print("Good")
elif marks >= 33:
print("Pass")
# Only ONE block executes!Output:
Key Rule: elif chain में केवल पहली matching condition का block execute होता है।Elif with Logical Operators
age = 25
income = 45000
if age < 18:
print("Minor — No loan")
print("नाबालिग — ऋण नहीं")
elif age >= 18 and income >= 50000:
print("Premium Loan Eligible ✓")
print("प्रीमियम ऋण योग्य ✓")
elif age >= 18 and income >= 25000:
print("Standard Loan Eligible ✓")
print("मानक ऋण योग्य ✓")
elif age >= 18 and income >= 15000:
print("Micro Loan Eligible")
print("माइक्रो ऋण योग्य")
else:
print("Income too low for any loan")
print("आय बहुत कम है, ऋण के लिए पात्र नहीं")Output (age=25, income=45000):
Standard Loan Eligible ✓ मानक ऋण योग्य ✓
Season Finder (मौसम पहचानकर्ता)
Output (month = 4):
Season: Spring — बसंत 🌸
Common Mistakes (सामान्य गलतियाँ)
❌ Mistake 1: elif before if
# WRONG
elif x > 5: # SyntaxError!
print("big")
# CORRECT
if x > 5:
print("big")
elif x > 0:
print("positive")❌ Mistake 2: Overlapping Ranges (order matters!)
marks = 85
# WRONG ORDER — will print wrong result
if marks >= 33:
print("Pass") # This triggers first! ❌
elif marks >= 60:
print("Good") # Never reached
elif marks >= 75:
print("Very Good") # Never reached
# CORRECT ORDER — from highest to lowest
if marks >= 90:
print("Excellent")
elif marks >= 75:
print("Very Good") # Correct ✓
elif marks >= 60:
print("Good")
elif marks >= 33:
print("Pass")❌ Mistake 3: Condition after else
# WRONG
if x > 10:
print("big")
elif x > 5:
print("medium")
else x > 0: # SyntaxError! else has no condition
print("small")
# CORRECT
if x > 10:
print("big")
elif x > 5:
print("medium")
elif x > 0:
print("small")
else:
print("zero or negative")❌ Mistake 4: Duplicate Conditions
x = 50
# REDUNDANT — both conditions same
if x > 40:
print("Greater than 40")
elif x > 40: # This will NEVER run
print("This never runs")Practice Exercises (अभ्यास प्रश्न)
Exercise 1 — Shopping Discount
Write a program where:
- Purchase >= 5000 → 20% discount
- Purchase >= 2000 → 15% discount
- Purchase >= 1000 → 10% discount
- Purchase >= 500 → 5% discount
- Less than 500 → No discount
Exercise 2 — Number Category
Categorize a number:
- Negative
- Zero
- Single digit (1-9)
- Double digit (10-99)
- Triple digit (100-999)
- Large (1000+)
Exercise 3 — Electricity Bill
Units consumed:
- 0-100: ₹1.50/unit
- 101-200: ₹2.50/unit
- 201-300: ₹4.00/unit
- Above 300: ₹6.00/unit
Exercise 4 — Age Category
- 0-2: Baby
- 3-12: Child
- 13-17: Teenager
- 18-59: Adult
- 60+: Senior Citizen
Exercise 5 — Rock Paper Scissors Game
Take user input and computer choice (hardcode), determine winner.
Solutions (हल)
Solution 1 — Shopping Discount
purchase = float(input("Enter purchase amount (₹): "))
if purchase >= 5000:
discount_pct = 20
elif purchase >= 2000:
discount_pct = 15
elif purchase >= 1000:
discount_pct = 10
elif purchase >= 500:
discount_pct = 5
else:
discount_pct = 0
discount = purchase * discount_pct / 100
final = purchase - discount
print(f"Discount: {discount_pct}% = ₹{discount:.2f}")
print(f"Final Amount: ₹{final:.2f}")Solution 4 — Age Category
age = int(input("Enter age: "))
if age < 0:
print("Invalid age!")
elif age <= 2:
print("Baby 👶")
elif age <= 12:
print("Child 🧒")
elif age <= 17:
print("Teenager 🧑")
elif age <= 59:
print("Adult 👨")
else:
print("Senior Citizen 👴")Summary Table (सारांश तालिका)
| Statement | Use Case | Condition? |
|---|---|---|
if | First condition | Yes |
elif | Additional conditions | Yes |
else | Default/fallback | No |
Execution Rule:
✅ Key Takeaways
- 📌
elif= "else if" — Python में multiple conditions check करने का तरीका - 📌
elifहमेशाifके बाद आता है — अकेलेelifuse नहीं कर सकते (SyntaxError) - 📌 एक
if-elif-elsechain में केवल एक block execute होता है — पहली True condition का block चलता है, बाकी skip - 📌 Condition order matters! — Higher/specific values पहले check करो, otherwise wrong block trigger होगा
- 📌
elseoptional है — अगर कोई condition match नहीं हुई तो else block चलेगा (fallback) - 📌 Multiple
ifvselif— multipleif= सब independently check होते हैं;elif= एक chain, एक ही execute - 📌 Logical operators (
and,or,not) कोelifconditions में combine कर सकते हैं - 📌
inoperator with lists —elif month in [1, 2, 3]जैसे grouping conditions possible - 📌 Real-world programs (Grade Calculator, BMI, Menu System) सब
elifपर based हैं - 📌
elifchain readability बढ़ाती है — multiple nestedif-elseसे better approach है
❓ FAQ
Q1: elif और else if में क्या difference है?
Answer: Python में else if लिखना invalid है। Python का syntax elif (shorthand) use करता है। C/Java में else if लिखते हैं, लेकिन Python में हमेशा elif लिखें।
# WRONG in Python
if x > 10:
print("big")
else if x > 5: # SyntaxError!
print("medium")
# CORRECT
if x > 10:
print("big")
elif x > 5: # ✅ Python way
print("medium")Q2: क्या हम elif without else use कर सकते हैं?
Answer: हाँ, बिल्कुल! else completely optional है। अगर आप default case handle नहीं करना चाहते तो else मत लिखें।
marks = 75
if marks >= 90:
print("Excellent")
elif marks >= 75:
print("Very Good")
elif marks >= 60:
print("Good")
# No else — if marks < 60, nothing happensQ3: कितने elif blocks एक chain में हो सकते हैं?
Answer: Python में कोई limit नहीं है! आप जितने चाहें उतने elif लिख सकते हैं। लेकिन अगर बहुत ज्यादा हैं (10+), तो dictionary mapping या match-case (Python 3.10+) consider करें।
Q4: elif chain में if block False हो और कोई elif True न हो तो क्या होगा?
Answer: अगर else block है तो वो execute होगा। अगर else भी नहीं है, तो कुछ भी execute नहीं होगा — program अगली line पर चला जाएगा।
Q5: क्या elif के अंदर nested if लिख सकते हैं?
Answer: हाँ! elif block के अंदर आप कोई भी valid Python code लिख सकते हैं — including nested if-elif-else।
age = 25
has_id = True
if age < 18:
print("Minor")
elif age >= 18:
if has_id:
print("Entry allowed ✅")
else:
print("Bring your ID!")Q6: elif vs multiple if — performance में difference?
Answer: हाँ! elif chain में जैसे ही एक condition True मिलती है, बाकी सब skip हो जाती हैं। Multiple if में सब conditions independently check होती हैं — unnecessary computation होती है।
Q7: क्या elif में = (assignment) use कर सकते हैं?
Answer: नहीं! Condition में हमेशा == (comparison) use करें। = (single equal) assignment है, condition नहीं — Python SyntaxError देगा।
# WRONG
elif x = 5: # SyntaxError!
# CORRECT
elif x == 5: # Comparison ✅Q8: elif chain में order कैसे decide करें?
Answer: Range-based conditions (>=, <=) में highest value first रखें (90 → 75 → 60 → 33)। Equality-based conditions (==) में order matter नहीं करता।
🎯 Interview Questions
Q1: What is elif in Python? Explain with syntax.
Answer: elif is short for "else if". It allows you to check multiple conditions in sequence. Only the first True condition's block executes.
if condition1:
# block 1
elif condition2:
# block 2
elif condition3:
# block 3
else:
# default blockKey point: It creates a mutually exclusive decision chain — only one block runs.
Q2: What is the difference between multiple if statements and an if-elif chain?
Answer:
- Multiple
if: Each condition is checked independently. Multiple blocks can execute. if-elifchain: Conditions are checked sequentially. As soon as one is True, the rest are skipped.
x = 85
# Multiple if — BOTH print
if x >= 60: print("Pass") # ✅ prints
if x >= 80: print("Merit") # ✅ prints
# elif chain — Only FIRST match prints
if x >= 80: print("Merit") # ✅ prints
elif x >= 60: print("Pass") # ❌ skippedQ3: Can elif exist without if? Why or why not?
Answer: No, elif cannot exist without a preceding if. It will raise a SyntaxError. elif is semantically "otherwise, if..." — it needs an initial condition to follow.
Q4: Why does order of conditions matter in an elif chain?
Answer: Because only the first True condition executes. If you put broader conditions first (e.g., marks >= 33 before marks >= 90), the broader condition matches first and more specific ones are never reached.
Always order from most restrictive to least restrictive.
Q5: How many elif blocks can you have in Python?
Answer: There is no technical limit. You can have as many elif blocks as needed. However, for readability and maintainability, if you exceed 8-10 conditions, consider using:
- Dictionary mapping
match-case(Python 3.10+)- Function dispatch tables
Q6: What happens if no condition in an if-elif chain is True and there is no else?
Answer: Nothing executes from that chain. The program simply moves to the next statement after the chain. No error is raised — it's perfectly valid.
Q7: Can you use elif with logical operators? Give an example.
Answer: Yes! elif conditions can include any valid Boolean expression including and, or, not, comparisons, and function calls.
age = 25
income = 60000
if age >= 18 and income >= 50000:
print("Premium eligible")
elif age >= 18 and income >= 25000:
print("Standard eligible")
elif age >= 18:
print("Basic eligible")
else:
print("Not eligible")Q8: Write a program using elif to convert percentage to letter grade (A, B, C, D, F).
Answer:
percentage = float(input("Enter percentage: "))
if percentage >= 90:
grade = "A"
elif percentage >= 80:
grade = "B"
elif percentage >= 70:
grade = "C"
elif percentage >= 60:
grade = "D"
else:
grade = "F"
print(f"Grade: {grade}")Enter percentage: 78 Grade: C
Q9: What is the difference between elif and nested if-else?
Answer:
elifcreates a flat, readable chain — all conditions at the same indentation level.- Nested
if-elsecreates deeper indentation and is harder to read.
Both achieve the same logic, but elif is preferred for linear multi-way decisions:
# elif (CLEAN) ✅
if x > 90: print("A")
elif x > 80: print("B")
elif x > 70: print("C")
# Nested if-else (MESSY) ❌
if x > 90: print("A")
else:
if x > 80: print("B")
else:
if x > 70: print("C")Q10: In an elif chain, if multiple conditions could be True, which one executes?
Answer: Always the first one (top to bottom). Once a True condition is found, its block executes and all remaining elif/else blocks are completely skipped — even if their conditions would also be True.
Next Topic (अगला विषय)
➡️ Nested If — if के अंदर if का उपयोग
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Elif Statement in Python.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, control, flow, elif
Related Python Master Course Topics