Antwoorden — Hoofdstuk 3: Selecties (if / elif / else)
Opmerking: Code is in het Engels, met korte Nederlandse toelichting erboven of eronder.
Antwoord 1 — Basis if
- Deelbaarheid door 2 bepaalt even/odd.
n = int(input("Enter an integer: "))
if n % 2 == 0:
print("even")
else:
print("odd")
Antwoord 2 — Leeftijdscategorieën
- Volgorde van drempels is belangrijk: strengste eerst of van hoog naar laag.
age = int(input("Age: "))
if age < 18:
print("minor")
elif age <= 64:
print("adult")
else:
print("senior")
Antwoord 3 — Rapportcijfer naar label
- Zorg dat intervallen elkaar niet overlappen en samen 0..10 afdekken.
score = float(input("Score (0-10): "))
if score < 5.5:
label = "insufficient"
elif score < 7.0:
label = "sufficient"
elif score < 8.5:
label = "good"
else:
label = "excellent"
print(label)
Antwoord 4 — Login-indicatie
- Eenvoudige en/conditie; geen echte beveiliging.
username = input("Username: ")
password = input("Password: ")
if username == "admin" and password == "secret":
print("Welcome!")
else:
print("Access denied")
Antwoord 5 — Korting met lidmaatschap
- Volgorde: eerst de strengere (lid + bedrag), dan de alternatieve drempel.
amount = float(input("Amount: "))
member = input("Member? (yes/no): ").strip().lower() == "yes"
if member and amount >= 100:
discount = 0.10
elif amount >= 150:
discount = 0.05
else:
discount = 0.0
final_price = amount * (1 - discount)
print(f"Discount: {discount*100:.0f}%")
print(f"Final price: {final_price:.2f}")
Antwoord 6 — Truthiness en invoer (ternary)
query = input("Search query: ").strip()
msg = "Empty query" if not query else f"Searching for '{query}'..."
print(msg)
Antwoord 7 — Kettingvergelijking 10..20
x = int(input("x: "))
print(10 <= x <= 20)
Antwoord 8 — Guard clause (functie)
- Vroeg stoppen bij ongeldige
weight_kgen dan per land beslissen.
def shipping_cost(country: str, weight_kg: float) -> float:
if weight_kg <= 0:
raise ValueError("Weight must be positive")
if country == "NL":
return 4.50 if weight_kg <= 2 else 6.75
elif country == "BE":
return 5.20 if weight_kg <= 2 else 7.40
else:
return 9.90
if __name__ == "__main__":
print(shipping_cost("NL", 1.5)) # 4.50
print(shipping_cost("BE", 3.0)) # 7.40
print(shipping_cost("DE", 0.5)) # 9.90
Antwoord 9 — Wachtwoordsterkte-indicatie (simpel)
pwd = input("Password: ")
length = len(pwd)
if length < 6:
label = "weak"
elif length <= 9:
label = "medium"
else:
label = "strong"
print(f"{label} (length={length})")
Antwoord 10 — Netto prijs met btw‑optie
amount = float(input("Amount: "))
mode = input("Type (incl/excl): ").strip().lower()
VAT = 0.21
if mode == "incl":
net = amount / (1 + VAT)
print(f"Net (ex VAT): {net:.2f}")
elif mode == "excl":
gross = amount * (1 + VAT)
print(f"Gross (incl VAT): {gross:.2f}")
else:
print("Unknown type; use 'incl' or 'excl'.")
Uitdaging (optioneel) — Kalenderdag naar type dag
day = input("Day name: ").strip().lower()
weekend = {"saturday", "sunday"}
label = "weekend" if day in weekend else "weekday"
print(label)