Python Conditions
Conditions program ko decisions lene deti hain. Is chapter me if, elif, else, comparisons, logical operators, truthy/falsy values, nested conditions, conditional expressions aur practical decision-making patterns samjhenge.
What is decision making?
Decision making means program kisi condition ko evaluate karke different code paths choose karta hai.
age = 20
if age >= 18:
print("Adult")age >= 18 ek condition hai. Agar result True hai to indented block run hota hai; agar False hai to block skip ho jata hai.
The if statement
if ke baad expression evaluate hota hai. Truthy result par block execute hota hai.
temperature = 34
if temperature > 30:
print("Hot day")
print("Weather checked")Indentation block membership define karti hai. Last line condition ke bahar hai.
if ... else
Jab exactly two branches chahiye, else fallback path provide karta hai.
score = 58
if score >= 60:
print("Pass")
else:
print("Try again")Only one branch runs.
Multiple branches with elif
elif additional conditions check karta hai. Python top-to-bottom evaluate karta hai and first truthy branch ke baad remaining branches skip ho jati hain.
score = 82
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
elif score >= 60:
grade = "C"
else:
grade = "D"
print(grade)Conditions with comparisons
Common comparison operators: ==, !=, <, <=, >, >=.
age = 21
if age == 21:
print("Exact match")
if age != 18:
print("Not eighteen")= assignment hai, == equality comparison.Readable range checks
Python chained comparisons ko naturally support karta hai.
age = 25
if 18 <= age <= 60:
print("Working-age range example")Ye age >= 18 and age <= 60 ke same intent ko compactly express karta hai.
Combine conditions with and, or, not
is_logged_in = True
is_verified = True
is_blocked = False
if is_logged_in and is_verified and not is_blocked:
print("Access granted")and— all required operands truthy hone chahiye.or— at least one operand truthy ho.not— truth value invert karta hai.
Short-circuit logic
and aur or zarurat na hone par right side evaluate nahi karte.
name = "Aman"
if name and len(name) >= 3:
print("Valid-looking name")First operand falsy ho to and ka right side skip ho sakta hai.
Truthy and falsy values
if ko literal True/False hi nahi, kisi bhi value ki truth value mil sakti hai.
name = ""
items = []
count = 0
if not name:
print("Name missing")
if not items:
print("No items")
if not count:
print("Count is zero")Common falsy values: False, None, numeric zero, empty strings and empty containers.
Check None with is
None checks ke liye identity style preferred hai.
result = None
if result is None:
print("No result yet")None ko zero ya empty string ke saath confuse mat karo.
Membership in conditions
role = "editor"
if role in ("admin", "editor"):
print("Can edit content")in lists, tuples, sets, strings and dictionaries ke saath later aur useful hoga.
Nested conditions
Ek condition ke andar another condition ho sakti hai.
logged_in = True
role = "admin"
if logged_in:
if role == "admin":
print("Admin dashboard")
else:
print("User dashboard")
else:
print("Please sign in")Empty branch with pass
Python block syntactically empty nahi ho sakta. Placeholder ke liye pass use ho sakta hai.
is_ready = False
if is_ready:
pass
else:
print("Still preparing")pass koi meaningful action perform nahi karta; it is a no-op placeholder.
Conditional expression
Simple two-value selection ke liye Python conditional expression support karta hai.
age = 20
label = "Adult" if age >= 18 else "Minor"
print(label)Complex branching ko one-line expression me force mat karo.
match statement — preview
Modern Python me match structural pattern matching provide karta hai. Ye simple if/elif ka universal replacement nahi hai, isliye beginner stage par recognize karna enough hai.
status = "paid"
match status:
case "paid":
print("Order confirmed")
case "pending":
print("Waiting for payment")
case _:
print("Unknown status")Conditions with user input
Input ko correct type me convert karke decision logic apply kar sakte ho.
age = int(input("Age: "))
if age < 0:
print("Invalid age")
elif age < 18:
print("Minor")
else:
print("Adult")Validate ranges before classification
Business logic me impossible inputs ko pehle reject karna useful hota hai.
percentage = 108
if percentage < 0 or percentage > 100:
print("Invalid percentage")
elif percentage >= 75:
print("Distinction")
elif percentage >= 60:
print("First division")
elif percentage >= 40:
print("Pass")
else:
print("Needs improvement")Validation ko classification se pehle rakhne se logic clearer hota hai.
Common beginner mistakes
=ko equality comparison ke liye use karna.if/elifke end me colon bhoolna.- Block indentation galat karna.
- Most general condition ko pehle rakhkar specific branch unreachable banana.
and/orko incorrectly combine karna.Noneko==se check karna instead of preferredis None.- Truthy/falsy behavior samjhe bina complex shortcuts use karna.
- Deep nested
ifstructures banana. - Invalid input ranges validate na karna.
- Complex logic ko unreadable one-line conditional expression me force karna.
Beginner best practices
- Conditions ko simple aur readable rakho.
- Branch order carefully choose karo.
- Repeated complex expressions ko meaningful variables me store karo.
- Impossible inputs ko early validate karo.
Nonechecks ke liyeis Noneuse karo.- Nested logic ko shallow rakhne ki koshish karo.
- Boundary values test karo: exactly 18, 60, 0, 100, etc.
Chapter checklist
if,elif,elseka flow clear hai?- Comparison operators use kar sakte ho?
and,or,notcombine kar sakte ho?- Truthiness/falsiness ka basic idea samajh aaya?
Noneko correctly check kar sakte ho?- Nested condition aur conditional expression ka difference clear hai?
- Branch order aur range validation ka importance samajh aaya?
Practice Task — Student Result Decision System
BrounStack Playground me ek result decision program banao.
- Student name input lo.
- Percentage as
floatinput lo. - Attendance percentage as
floatinput lo. - 0–100 range ke bahar values ko invalid mark karo.
- Attendance 75 se kam ho to eligibility message do.
- Valid and eligible student ko percentage ke basis par grade do.
90+→ A,75+→ B,60+→ C,40+→ Pass, otherwise Needs Improvement.- At least one
andcondition use karo. - At least one
orcondition use karo. - Output f-string ke through readable banao.
- Boundary values 40, 60, 75, 90 test karo.
- Invalid percentage like 120 test karo.
- Final working program clean indentation ke saath run karo.