HomeCourseModule 04 › if / else — making decisions

if / else — making decisions

Module 04 · Control Flow8 min readBeginner

What you'll learn

  • Write if / elif / else blocks
  • Use indentation correctly
  • Refactor nested ifs into clean code

The shape of an if-statement

age = 18

if age >= 18:
    print("Adult")
else:
    print("Minor")

Notice three things:

elif — chained conditions

Like IFS() in Excel:

score = 73

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(grade)   # C

One-line if (when it improves readability)

status = "VIP" if total > 1000 else "regular"

Use sparingly. Multi-line is usually clearer.

The "early return / guard" pattern

Nested ifs get ugly fast. Flatten them with early returns:

# Tangled
def process(order):
    if order is not None:
        if order["status"] == "paid":
            if order["amount"] > 0:
                ship(order)

# Cleaner
def process(order):
    if order is None: return
    if order["status"] != "paid": return
    if order["amount"] <= 0: return
    ship(order)

Walkthrough: pricing tiers

Inputs

customer_type = "wholesale"
quantity = 250

Compute the discount

if customer_type == "wholesale":
    if quantity >= 500:
        discount = 0.20
    elif quantity >= 100:
        discount = 0.10
    else:
        discount = 0.05
elif customer_type == "vip":
    discount = 0.15
else:
    discount = 0.00

print(f"{discount*100:.0f}% discount")   # 10% discount

Key takeaways

  • Colon at the end of if/elif/else, indent the body.
  • elif chains conditions; else catches everything left.
  • Flatten deep nesting with early returns.

Shipping cost calculator

Free shipping over $100. $5 flat if weight < 1kg. Otherwise $15. Write the if/elif/else.

📹 Video walkthrough
A video walkthrough of this lesson will be embedded here. Until then, the written walkthrough above mirrors what the video will cover step-for-step.