if - elif - else — syntax, indentation rules
1.2.15· Coding › Introduction to Programming (Python)
YEH KYUN exist karta hai?
YEH HAI KYA
SYNTAX KAISI DIKHTI HAI
if condition1:
# block A — runs if condition1 is True
statement_a
elif condition2:
# block B — runs if condition1 False AND condition2 True
statement_b
else:
# block C — runs if both above were False
statement_cExactly ek kyun run karna chahiye (else ke saath)? Conditions saari possibilities partition karti hain: ya toh koi pehla True wala hai, ya koi nahi → else. Cases ka set bina overlap ke covered hai. Isliye ek clean if/elif/else chain exhaustive aur exclusive hoti hai.

Derivation: Python indentation kaise padhta hai
Worked examples
Common mistakes (Steel-man + fix)
Recall Feynman: ek 12 saal ke bachche ko samjhao
Ek hallway imagine karo jisme doors hain. Tum chalte ho aur pehle door par likha sawaal poochte ho: "Kya yeh sach hai?" Agar haan, tum us door se andar jaate ho aur hallway khatam ho jaata hai — baaki doors check nahi hote. Agar nahi, tum agli door (elif) par chalte ho aur phir poochte ho. Agar tum end tak pahunch gaye aur kisi door ne haan nahi kaha, toh tum else likha aakhri door se andar jaate ho. Jis tarah tum apne sentences ko thoda right mein push karte ho, usi tarah tum actions ke ek set ko ek khaas door se jodh rahe ho — saath mein push in kiya hua sab kuch us door se jaane ke baad hota hai.
Active recall
Kaun sa punctuation mark har if, elif, aur else line ke end mein hona chahiye?
:Python ko kaise pata chalta hai ki kaun si lines if block ke andar belong karti hain?
Ek if chain mein kitne elif blocks ho sakte hain?
Ek if chain mein kitne else blocks ho sakte hain?
Ek if/elif/elif/else chain mein kitne blocks run hote hain?
else agar koi nahi).Tabs aur spaces mix karne se kaun sa error aata hai?
TabError: inconsistent use of tabs and spaces.Ek condition mein = aur == mein kya fark hai?
= value assign karta hai; == equality test karta hai. Conditions ko == chahiye.Kai alag ifs ki jagah elif kyun prefer karein?
elif branches ko mutually exclusive banata hai aur pehle match par ruk jaata hai; alag ifs sab run hote hain aur results overwrite kar sakte hain.score=70 ke liye ek chain mein jo >=90, >=80, >=70, else check karti hai, kya select hoga?
>=70 branch (pehla True wala).Python mein indentation ke ek level mein standard kitne spaces hote hain?
Connections
- Booleans and comparison operators — conditions
True/Falseevaluate hoti hain - Logical operators and, or, not — compound conditions banana
- Truthiness in Python —
ifmein non-bool values (0, "", [] are False) - Indentation and code blocks — yahi rule loops aur functions par bhi apply hota hai
- while and for loops —
:aur indented blocks use karte hain - match-case statement — alternative branching (Python 3.10+)
- Ternary conditional expression —
a if cond else bone-liner