A conditional selects which instructions run by checking whether a condition is true or false.
Build if/elif/else decisions and test overlapping rules, exact boundaries and the order in which conditions are checked.
A program can evaluate several true facts and still choose the wrong action. The first example has exactly that bug: two price bands overlap. Follow which branch is reached, then check the boundary values and rewrite the same decision with guards while preserving its behavior.

Compare overlapping price bands
This exercise uses invented billing rules, not current tax guidance: above
₹7,500 the rate is 18%, above ₹1,000 it is 12%, and otherwise it is zero.
The function is named gst_rate in the exercises. First attempt:
def gst_rate(price):
if price > 1000:
return 0.12
elif price > 7500:
return 0.18
else:
return 0.0
print(gst_rate(9000))Every expensive item is under-taxed. When conditions overlap, put the narrowest one first:
Run it and see the ₹9,000 item taxed at 12%. Reorder the checks.
The same fictional system marks a bill for review if it is over ₹5,000
and a registration field is nonempty. and needs both sides true, or needs just one, and not flips
True/False:
if gst_number: works because empty means false. A blank form field
arrives as "", and 0, "", [], {} and None all count as false.
Preparing this topic’s interactive investigation…
Audit the boundary, not just the example
Two independent if statements can both run. An if/elif chain makes
one decision: after a true condition, remaining branches are skipped.
For the price bands, the set “above 7,500” sits inside “above 1,000”; testing
the larger set first hides the smaller one.
| Price | Above 7,500? | Above 1,000? | Intended rate |
|---|---|---|---|
| 1,000 | no | no | 0% |
| 1,001 | no | yes | 12% |
| 7,500 | no | yes | 12% |
| 7,501 | yes | yes | 18% |
The table catches changing > to >=, which testing only 9,000 cannot.
For continuous prices, also try a fractional amount either side of a boundary.
Conditions use truth testing: they need not literally produce bool.
and stops at the first falsy operand; or at the first truthy operand.
Thus name and name[0] == "A" avoids indexing an empty string, while
price or default wrongly replaces a valid zero price. Use an explicit
price is None when only missing values should fall back.
Book a cab
A cab app decides whether to confirm a ride. The first version nests:
def book(user, seats_free, paid):
if user:
if seats_free > 0:
if paid:
return "confirmed"
else:
return "pay first"
else:
return "no cabs nearby"
else:
return "log in first"It works, but the reason for each "no" is far from its check. Flip it: throw out each bad case as soon as you see it (a guard clause), and the happy path ends up flat at the bottom:
Nesting is still fine when the inner choice truly depends on the outer one (a senior discount that is bigger for members). Once it goes three levels deep, use guard clauses instead.
Delivery status
A delivery app turns a status code into a message. When you compare one
value against a list of fixed options, match / case (Python 3.10+)
reads like a lookup table:
Only one case runs, with no fall-through and no break.
Two one-liners you'll use daily
Trap:
tip or 10replaces a real tip of0with10, because0is falsy. When0is a valid answer, writetip if tip is not None else 10.
A guard-clause rewrite should keep the same answers for all supported
inputs. In the cab example, seats_free <= 0 rejects zero and negative
counts, matching the original seats_free > 0 success branch. Returning
early also fixes which rejection wins when several facts are bad.
Specify admission with three facts: registration, age at least 16, and seats available. Write the decision table for exactly age 16, zero seats, and an unregistered person who is also too young. Choose which message has priority, then implement nested and guard versions. Their outputs should agree. The later password exercise is a toy branching rule, not an assessment of real password security.
Quick practice
name = "0"
if name:
print("got a name")
else:
print("blank")temp = 30
if temp > 15:
print("mild")
elif temp > 25:
print("hot")
else:
print("cold")print(True or False and False)A 15-year-old is being allowed to vote. Find the one word that is wrong.
🎯 Your turn
Two functions, the same decision written two ways. Check runs the tests for both.
Task 1: apply_discount(bill, code) with if / elif / else. Return the
bill after the code, rounded to two decimals. SAVE10 10% off ·
STUDENT 15% off · HALF 50% off · anything else, no discount.
apply_discount(100, "SAVE10")→90.0apply_discount(100, "")→100.0
Task 2: discount_rate(code) with match / case. Return the rate itself
(a number), with one case per code and case _ for the rest.
discount_rate("SAVE10")→0.1discount_rate("NOPE")→0.0
Hint: 10% off means you pay 90%, so bill * 0.90. Task 2 is match code:
with a case "SAVE10": per code and a final case _:.
Press ▶ Run, try the Live App chips, then ✓ Check. After that, the practice set below goes from warm-up to a mini request router.
Practice — level up
0/5 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write sign(n) returning "positive", "negative" or "zero".
Write clamp(n, lo, hi) that returns n limited to the range lo..hi — below lo gives lo, above hi gives hi. Use a ternary.
Write checkout_status(total, coupon, is_member).
total <= 0→"empty cart"- Free shipping if the customer is a member OR
total >= 50, else$5. - Discount: coupon
"VIP"and member → 20% off; coupon"SAVE10"→ 10% off; else none. - Return
f"pay $<final>, shipping <FREE|$5>"withfinalto 2 decimals.
Write password_strength(pw) scoring these 5 rules — length ≥ 8, has a digit, an uppercase, a lowercase, a symbol (non-alphanumeric). Return "strong" (≥4 rules), "ok" (≥2), else "weak".
Write route_request(method, path, is_admin) using match on (method, path):
GET /→"home";GET /health→"ok"GET /admin→"admin panel"ifis_adminelse"403 forbidden"POST /login→"logging in"- anything else →
f"404 <method> <path>"