Why do we need decisions?#
Real programs must behave differently in different situations:
- If the password is correct → log in, otherwise → show an error.
- If the bill is above Rs. 1000 → give a discount.
- If marks are below 33 → result is "Fail".
Python makes decisions using if, elif and else.
The if statement#
if condition:
# code that runs only when condition is True
conditionis any expression that givesTrueorFalse(usually a comparison).- The colon
:is required. - The code inside must be indented (4 spaces).
Change temperature to 25 and run again - the two indented lines are skipped.
The if...else statement#
else gives an alternative when the condition is False:
Exactly one of the two blocks runs - never both, never neither.
The if...elif...else ladder#
When there are more than two possibilities, use elif ("else if"):
Python checks the conditions from top to bottom and runs only the first block whose condition is True. The rest are skipped.
if-elif-else को एक सीढ़ी (ladder) की तरह समझें। Python ऊपर से नीचे एक-एक condition जाँचता है। जैसे ही कोई condition True मिलती है, उसी का block चलता है और बाकी सभी conditions छोड़ दी जाती हैं।
ऊपर के example में marks = 68 है। पहली condition (68 >= 75) False है, दूसरी (68 >= 60) True है - इसलिए "First division" print होता है, और नीचे की conditions check ही नहीं होतीं।
इसीलिए क्रम (order) बहुत ज़रूरी है - सबसे बड़ी range पहले लिखें।
Order matters. This version is wrong:
if marks >= 33:
print("Third division")
elif marks >= 75:
print("Distinction") # never reached for 80, because 80 >= 33 is already True
Several ifs vs if-elif#
x = 15
if x > 10: print("big")
if x > 5: print("medium") # separate if - also checked
This prints both lines. With elif, only the first match would print. Use separate ifs when the checks are independent, and elif when they are alternatives.
Combining conditions#
Use and, or, not:
Nested if#
An if inside another if:
Deep nesting (3-4 levels) becomes hard to read. Often you can flatten it with and or with elif.
Truthy and falsy conditions#
The condition doesn't have to be a comparison. Any value works - empty/zero values are treated as False:
Conditional expression (one-line if-else)#
value_if_true if condition else value_if_false
The pass placeholder#
A block can't be empty. If you haven't written it yet, use pass:
if score > 100:
pass # TODO: handle bonus later
match-case (Python 3.10+)#
When you compare one value against many fixed options, match is cleaner than a long elif chain:
case _ is the default (like else). | means "or".
Practical example: electricity bill#
Summary#
if condition:runs a block only when the condition is True.else:runs when it is False.elifchecks further conditions - only the first True branch runs.- Combine conditions with
and,or,not; nestifs when needed. - Empty/zero values are falsy.
- One-line form:
x if condition else y. For many fixed options, usematch-case.