Antwoorden — Hoofdstuk 2: Invoer en uitvoer
Opmerking: Code is in het Engels, met korte Nederlandse toelichting erboven of eronder.
Antwoord 1 — Begroeting
- We trimmen spaties met
.strip()en gebruiken een f-string.
first = input("First name: ").strip()
print(f"Hello, {first}!")
Antwoord 2 — Volledige naam
first = input("First name: ").strip()
last = input("Last name: ").strip()
print(f"{last}, {first}")
print(f"{first} {last}")
Antwoord 3 — Bedrag netjes tonen (komma of punt)
raw = input("Amount: ").strip().replace(",", ".")
amount = float(raw)
print(f"Amount: {amount:.2f}")
Antwoord 4 — Percentage format
rate = float(input("Rate (e.g. 0.075): ").strip().replace(",", "."))
print(f"Rate: {rate:.1%}")
Antwoord 5 — Kleine bon (uitlijning)
name = input("Item name: ").strip()
qty = int(input("Quantity: ").strip())
price = float(input("Unit price: ").strip().replace(",", "."))
total = qty * price
print(f"{'Item':<10}{'Qty':>5}{'Price':>8}{'Total':>8}")
print(f"{name:<10}{qty:>5}{price:>8.2f}{total:>8.2f}")
Antwoord 6 — Print parameters
print("a", "b", "c", sep=", ", end="!")
Antwoord 7 — Voortgangspunten
- Twee varianten: vijf losse prints of een kleine lus.
# Simple repeated prints
print(".", end="", flush=True)
print(".", end="", flush=True)
print(".", end="", flush=True)
print(".", end="", flush=True)
print(".", end="", flush=True)
# With a small loop (acceptable here)
for _ in range(5):
print(".", end="", flush=True)
Antwoord 8 — Foutmelding via stderr
import sys
raw = input("Enter integer: ").strip()
try:
n = int(raw)
print(f"OK: {n}")
except ValueError:
sys.stderr.write("Warning: not an integer\n")
Antwoord 9 — Unicode check
# Expect to see the characters rendered correctly in a UTF-8 capable terminal
print("café • naïve • € • λ")
Antwoord 10 — Command-line argument (teaser)
import sys
name = sys.argv[1] if len(sys.argv) > 1 else "world"
print(f"Hello, {name}!")
Uitdaging (optioneel) — Totaal met BTW en korting
raw_amount = input("Amount: ").strip().replace(",", ".")
amount = float(raw_amount)
raw_discount = input("Discount (0-100): ").strip().replace(",", ".")
discount_pct = float(raw_discount)
after_discount = amount * (1 - discount_pct / 100)
vat_rate = 0.21
vat_value = after_discount * vat_rate
final_total = after_discount + vat_value
print(f"Amount: {amount:>8.2f}")
print(f"Discount: {discount_pct:>8.1f}%")
print(f"After discount: {after_discount:>8.2f}")
print(f"VAT (21%): {vat_value:>8.2f}")
print(f"Total: {final_total:>8.2f}")