Making Decisions · Lesson 9 of 39
if, elif and else
Up to now, every program ran every line. Real programs choose: show the dashboard if the login is correct, otherwise show an error. In Python that choice is made with if, elif and else.
In this lesson
- The
ifstatement and its flowchart - Two-way (
else) and many-way (elif) decisions - Nested conditions and how to flatten them
- The one-line conditional expression
The if statement
temperature = 38
if temperature > 35:
print("It's hot – drink water!")
print("Have a good day.")
It's hot – drink water! Have a good day.
Three things make up an if: the keyword, a condition (anything that is truthy or falsy) and a colon. The indented lines below form the block that runs only when the condition is true.
if … else: two paths
balance = 1200
price = 1500
if balance >= price:
print("Payment successful")
balance -= price
else:
print(f"Insufficient balance. You need ₹{price - balance} more.")
Insufficient balance. You need ₹300 more.
if … elif … else: many paths
Use elif ("else if") to test several conditions in order. Python runs the first block whose condition is true and skips the rest.
marks = 82
if marks >= 90:
grade = "A+"
elif marks >= 75:
grade = "A"
elif marks >= 60:
grade = "B"
elif marks >= 40:
grade = "C"
else:
grade = "Fail"
print(f"Marks {marks} → Grade {grade}")
Marks 82 → Grade A
How Python walks through the chain (marks = 82)
- marks >= 90?No → try the next condition
- marks >= 75?Yes → grade = "A"
- Remaining elif / elseSkipped entirely
- print(...)Continues after the whole if-chain
Common mistake: conditions in the wrong order
If you test marks >= 40 first, a 95 would get a "C", because that is the first true condition. Put the most specific (highest) checks first. Similarly, a chain of separate if statements is not the same as if/elif: separate ifs are all checked, so several can run.
Nested conditions
You can put an if inside another. It works, but deep nesting quickly becomes hard to read:
is_logged_in = True
role = "editor"
if is_logged_in:
if role == "admin":
print("Full access")
else:
print("Limited access")
else:
print("Please log in")
Limited access
Often you can flatten nesting with and, or by handling the "bad" case first. This style – called a guard clause – is common in professional code:
def access_level(is_logged_in, role):
if not is_logged_in:
return "Please log in"
if role == "admin":
return "Full access"
return "Limited access"
print(access_level(True, "admin"))
print(access_level(False, "admin"))
Full access Please log in
(Functions are covered properly in chapter 9 – here just notice how flat and readable the logic becomes.)
The conditional expression (one-line if)
When you only need to pick between two values, write it on one line: value_if_true if condition else value_if_false.
age = 16
status = "adult" if age >= 18 else "minor"
print(status)
items = 1
print(f"{items} item{'s' if items != 1 else ''} in cart")
minor 1 item in cart
Keep it for simple choices. If you find yourself nesting conditional expressions, go back to a normal if statement.
Truthy conditions
Because every value is truthy or falsy, you can write natural checks without comparing to True, 0 or "":
cart = []
coupon = "SAVE10"
if not cart:
print("Your cart is empty")
if coupon:
print(f"Coupon {coupon} applied")
Your cart is empty Coupon SAVE10 applied
Write if cart: rather than if len(cart) > 0: and if is_valid: rather than if is_valid == True:. Both are shorter and more "Pythonic".
An empty block: pass
A block can't be empty. While you are still writing code, use pass as a placeholder:
score = 0
if score > 100:
pass # TODO: award a badge
print("done")
done
Real example: electricity bill
Slab-based pricing is a perfect if/elif problem. First 100 units cost ₹3, the next 100 cost ₹5, everything above 200 costs ₹8:
units = 260
if units <= 100:
bill = units * 3
elif units <= 200:
bill = 100 * 3 + (units - 100) * 5
else:
bill = 100 * 3 + 100 * 5 + (units - 200) * 8
print(f"{units} units → ₹{bill}")
260 units → ₹1280
Practice
Try it yourself
Given three numbers, print the largest without using
max().Show solution
a, b, c = 14, 31, 9 if a >= b and a >= c: largest = a elif b >= c: largest = b else: largest = c print(largest)31
Classify a BMI value: below 18.5 underweight, below 25 normal, below 30 overweight, otherwise obese.
Show solution
weight, height = 68, 1.72 bmi = weight / height ** 2 if bmi < 18.5: label = "underweight" elif bmi < 25: label = "normal" elif bmi < 30: label = "overweight" else: label = "obese" print(f"BMI {bmi:.1f}: {label}")BMI 23.0: normal
Quick check
In an if/elif chain, how many blocks can run?
At most one – the first whose condition is true (or the else block if none are).
Rewrite as one line: if x > 0: sign = "+" else: sign = "-"
sign = "+" if x > 0 else "-"
What does pass do?
Nothing. It is a placeholder for a block that must exist but has no code yet.
Summary
ifruns a block when its condition is truthy;elsehandles the rest.elifchains are checked top to bottom; only the first match runs.- Prefer guard clauses and
andover deep nesting. a if condition else bpicks between two values in one line.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.