LearningPython TutorialConditions
CHAPTER 6 · CONTROL FLOW

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.

English + Hinglish52 min readOnline practice included

What is decision making?

Decision making means program kisi condition ko evaluate karke different code paths choose karta hai.

decision.pyPython
age = 20

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

age >= 18 ek condition hai. Agar result True hai to indented block run hota hai; agar False hai to block skip ho jata hai.

Try if →

The if statement

if ke baad expression evaluate hota hai. Truthy result par block execute hota hai.

if-basic.pyPython
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.

if-else.pyPython
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.

grades.pyPython
score = 82

if score >= 90:
    grade = "A"
elif score >= 75:
    grade = "B"
elif score >= 60:
    grade = "C"
else:
    grade = "D"

print(grade)
Order matters: Broader condition pehle rakh doge to later specific branch unreachable ho sakti hai.

Run grade logic →

Conditions with comparisons

Common comparison operators: ==, !=, <, <=, >, >=.

comparisons.pyPython
age = 21

if age == 21:
    print("Exact match")

if age != 18:
    print("Not eighteen")
Remember: = assignment hai, == equality comparison.

Readable range checks

Python chained comparisons ko naturally support karta hai.

range.pyPython
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

logical.pyPython
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.

safe-check.pyPython
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.

truthy.pyPython
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.

none-check.pyPython
result = None

if result is None:
    print("No result yet")

None ko zero ya empty string ke saath confuse mat karo.

Membership in conditions

membership.pyPython
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.

nested.pyPython
logged_in = True
role = "admin"

if logged_in:
    if role == "admin":
        print("Admin dashboard")
    else:
        print("User dashboard")
else:
    print("Please sign in")
Readability: Deep nesting code ko difficult bana sakti hai. Conditions combine karna ya later functions/guard clauses use karna often cleaner hota hai.

Empty branch with pass

Python block syntactically empty nahi ho sakta. Placeholder ke liye pass use ho sakta hai.

pass.pyPython
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.

conditional-expression.pyPython
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.

match-preview.pyPython
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-check.pyPython
age = int(input("Age: "))

if age < 0:
    print("Invalid age")
elif age < 18:
    print("Minor")
else:
    print("Adult")

Try with stdin →

Validate ranges before classification

Business logic me impossible inputs ko pehle reject karna useful hota hai.

percentage.pyPython
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/elif ke end me colon bhoolna.
  • Block indentation galat karna.
  • Most general condition ko pehle rakhkar specific branch unreachable banana.
  • and/or ko incorrectly combine karna.
  • None ko == se check karna instead of preferred is None.
  • Truthy/falsy behavior samjhe bina complex shortcuts use karna.
  • Deep nested if structures 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.
  • None checks ke liye is None use karo.
  • Nested logic ko shallow rakhne ki koshish karo.
  • Boundary values test karo: exactly 18, 60, 0, 100, etc.

Chapter checklist

  • if, elif, else ka flow clear hai?
  • Comparison operators use kar sakte ho?
  • and, or, not combine kar sakte ho?
  • Truthiness/falsiness ka basic idea samajh aaya?
  • None ko 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.

  1. Student name input lo.
  2. Percentage as float input lo.
  3. Attendance percentage as float input lo.
  4. 0–100 range ke bahar values ko invalid mark karo.
  5. Attendance 75 se kam ho to eligibility message do.
  6. Valid and eligible student ko percentage ke basis par grade do.
  7. 90+ → A, 75+ → B, 60+ → C, 40+ → Pass, otherwise Needs Improvement.
  8. At least one and condition use karo.
  9. At least one or condition use karo.
  10. Output f-string ke through readable banao.
  11. Boundary values 40, 60, 75, 90 test karo.
  12. Invalid percentage like 120 test karo.
  13. Final working program clean indentation ke saath run karo.

Open practice starter →