Cohort 4Register

PART 1 · PYTHON FROM ZERO · LESSON 7

Making decisions: if, elif, else

FreeLesson 9 of 78

if runs a block of code only when a condition is True. elif and else handle the other cases.

ONE DECISION, THREE OUTCOMESPYTHON 3.12
amount = 1198

if amount >= 2000:
    bucket = "large"
elif amount >= 1000:            # checked only if the first was False
    bucket = "medium"
else:                           # none of the above
    bucket = "small"

print(amount, "->", bucket)

Output

1198 -> medium
A REAL BUSINESS RULEPYTHON 3.12
def delivery_fee(amount, city, is_member):
    if is_member:
        return 0
    if city in ["Bengaluru", "Mumbai", "Delhi"]:
        if amount >= 500:                    # an if inside an if
            return 0
        return 40
    return 80

print(delivery_fee(300, "Pune", True))
print(delivery_fee(799, "Mumbai", False))
print(delivery_fee(300, "Mumbai", False))
print(delivery_fee(300, "Pune", False))

Output

0
0
40
80

Each return leaves the function immediately, so once a rule matches, the rest is skipped. This style, called early return, keeps nesting shallow.

ONE-LINE IF, AND MATCHPYTHON 3.12
amount = 796
label = "free delivery" if amount >= 500 else "pay delivery"
print(label)

status = "returned"
match status:                     # Python 3.10+
    case "delivered":
        print("count the revenue")
    case "cancelled" | "returned":
        print("exclude from revenue")
    case _:
        print("unknown status")

Output

free delivery
exclude from revenue

Try it yourself before moving on

  1. Grade an order: 2,000 or more is "A", 1,000 or more is "B", otherwise "C".
  2. Check if a year is a leap year: divisible by 4, but not by 100 unless also by 400.
  3. Rewrite delivery_fee using match instead of if.