Skip to the workspace
Pebellslearn by building
Fundamentals  ›  Lesson

Conditionals

Conditionals 21 minA conditional selects which instructions run by checking whether a condition is true or false.

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.

A till checking a STUDENT coupon: the SAVE10 check says no, the STUDENT check says yes and the bill drops to 85%, and the HALF and else checks below are greyed out because they are never read

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:

What does this print?
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:

broken — fix it

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:

python

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:

python

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:

python

Only one case runs, with no fall-through and no break.

Two one-liners you'll use daily

python

Trap: tip or 10 replaces a real tip of 0 with 10, because 0 is falsy. When 0 is a valid answer, write tip 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

What does this print?
name = "0"
if name:
    print("got a name")
else:
    print("blank")
What does this print?
temp = 30
if temp > 15:
    print("mild")
elif temp > 25:
    print("hot")
else:
    print("cold")
What does this print?
print(True or False and False)
broken — fix it

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.0
  • apply_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.1
  • discount_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.

Your task
Two ways to choose. 1) Build apply_discount(bill, code) with if/elif/else — it returns the discounted bill (SAVE10 10% off, STUDENT 15%, HALF 50%, else none). 2) Build discount_rate(code) with match/case — it returns the rate itself (0.1, 0.15, 0.5, or 0.0). Examples: apply_discount(100, "SAVE10") → 90.0 · discount_rate("SAVE10") → 0.1.

Practice — level up

0/5 solved

Solve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.

Warm-upSign of a number

Write sign(n) returning "positive", "negative" or "zero".

conditionals
DrillClamp into a range

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.

ternarychained-comparison
BuildCheckout status

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>" with final to 2 decimals.
guardsand/orternaryf-strings
BossPassword strength

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".

any/allstring-methodsconditionals
CapstoneMini request router

Write route_request(method, path, is_admin) using match on (method, path):

  • GET / → "home"; GET /health → "ok"
  • GET /admin → "admin panel" if is_admin else "403 forbidden"
  • POST /login → "logging in"
  • anything else → f"404 <method> <path>"
matchguardsf-strings
Project context and further resources
You're building a piece ofBill Splitter & Tip Calculator
This piece — apply_discount(): Applies codes like SAVE10 / HALF to the bill.
Scenario A student in the group enters the code STUDENT at checkout, so the app must knock 15% off the bill.
apply_discount.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
apply_discount(bill, code) → floatReturn the bill after the discount code is applied.
try:
returned
discount_rate(code) → floatReturn the discount rate for a code, written with match/case.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.