🟢 Beginner · Lesson 08
if, elif और else Statements
Decision Making
Programs को अक्सर condition के आधार पर चुनना पड़ता है कि क्या करें। if statement block तभी चलाता है जब उसकी condition True हो।
if / elif / else Syntax
Python – syntax
if condition1:
# condition1 True होने पर चलता है
elif condition2:
# condition1 False और condition2 True पर
else:
# ऊपर सब False होने पर- हर condition colon
:से खत्म होती है। - उसके नीचे का block indent (4 spaces) होता है।
elif= "else if"; कई हो सकते हैं।elseoptional है।
Program 1: Pass या Fail
Python – passfail.py
marks = int(input("Enter marks: "))
if marks >= 33:
print("Result: PASS")
else:
print("Result: FAIL")Enter marks: 45
Result: PASS
अगर marks 33 या ज़्यादा है तो पहला block चलता है; वरना else block।
Program 2: तीन Numbers में सबसे बड़ा
Python – largest.py
a = int(input("a: "))
b = int(input("b: "))
c = int(input("c: "))
if a >= b and a >= c:
print("Largest is", a)
elif b >= c:
print("Largest is", b)
else:
print("Largest is", c)a: 5
b: 9
c: 2
Largest is 9
- पहले check करें कि
aदोनों से बड़ा है या नहीं। - नहीं तो
elif b >= cb और c में से तय करता है। - वरना
cसबसे बड़ा।
Program 3: Grade Calculator
Python – grade.py
pct = float(input("Enter percentage: "))
if pct >= 90:
grade = "A+"
elif pct >= 75:
grade = "A"
elif pct >= 60:
grade = "B"
elif pct >= 33:
grade = "C"
else:
grade = "Fail"
print("Grade:", grade)Enter percentage: 82
Grade: A
Python हर elif को ऊपर से नीचे check करता है और पहले true पर रुक जाता है — इसलिए order ज़रूरी है (सबसे ऊँचा पहले)।
Program 4: Positive, Negative या Zero
Python – signcheck.py
n = int(input("Enter a number: "))
if n > 0:
print("Positive")
elif n < 0:
print("Negative")
else:
print("Zero")Enter a number: -4
Negative
Nested if
दो-level decision के लिए एक if दूसरे if के अंदर रह सकता है।
Python – nested.py
age = int(input("Age: "))
if age >= 18:
has_id = input("Have ID? (yes/no): ")
if has_id == "yes":
print("Allowed to vote")
else:
print("Bring your ID")
else:
print("Too young to vote")सामान्य गलतियाँ
- condition में
==की जगह=लगाना। - colon
:भूलना। - block के अंदर गलत indentation।
elifconditions गलत order में रखना।
Practice Tasks
- Check करें कि number even है या odd।
- एक year लेकर leap year check करें।
- Age पूछकर child / teen / adult / senior print करें।
- तीन sides लेकर check करें कि triangle बन सकता है या नहीं।
सारांश
ifcondition True होने पर block चलाता है।elifऔर choices जोड़ता है;elsefallback है।- Conditions को colon और indented block चाहिए।
eliforder ज़रूरी — सबसे ऊँचा/specific पहले check करें।
💻 लाइव कोड एडिटर
इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.