MATCH Mini Project — Vending Machine.
The problem...
A vending machine has one job. You pick a product. You insert money. It tells you the price, confirms the purchase, and gives you your change.
Simple logic. Multiple cases. A perfect job for match.
The idea!
match handles the product selection. Guards handle the payment logic. One clean structure — no long if / elif chain in sight.
The menu
# water — 1.00 EUR
# coffee — 2.00 EUR
# chips — 1.50 EUR
# chocolate — 2.50 EUR
Your mission
Ask the user for a product and the amount inserted. Use match to find the price. Calculate and print the change — or tell them if it's not enough.
The solution
print("Available: water / coffee / chips / chocolate")
product = input("Choose a product: ").lower()
amount = float(input("Insert amount (EUR): "))
match product:
case "water":
price = 1.00
case "coffee":
price = 2.00
case "chips":
price = 1.50
case "chocolate":
price = 2.50
case _:
print("Product not found.")
price = None
if price is not None:
if amount >= price:
change = amount - price
print(f"{product.capitalize()} dispensed.")
print(f"Change: {change:.2f} EUR")
else:
print(f"Insufficient funds. {product.capitalize()} costs {price:.2f} EUR.")
Test it
# Choose a product: coffee
# Insert amount (EUR): 5
# Coffee dispensed.
# Change: 3.00 EUR
# Choose a product: chips
# Insert amount (EUR): 1
# Insufficient funds. Chips costs 1.50 EUR.
# Choose a product: pizza
# Product not found.
What's really happening
match identifies the product and sets the price. case _ catches anything that's not on the menu — and sets price to None so the payment logic knows to skip. The if after the match handles the rest.
Go further
- Add more products to the menu
- What happens if the user inserts exactly the right amount? Does it still work?
- Add a "sold out" case for one product —
case "water": print("Sold out.")
What you should understand now
matchidentifies the case —ifhandles the logic aftercase _catches unknown input — always handle itNoneis a safe sentinel value — "nothing was set":.2fformats floats to 2 decimal places — prices look clean