age = 18
if age >= 18:
print("Adult")
else:
print("Minor")
Notice three things:
if and else lines.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
status = "VIP" if total > 1000 else "regular"
Use sparingly. Multi-line is usually clearer.
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)
customer_type = "wholesale"
quantity = 250
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
if/elif/else, indent the body.elif chains conditions; else catches everything left.Free shipping over $100. $5 flat if weight < 1kg. Otherwise $15. Write the if/elif/else.