import sys, os, time
items = [
{"name": "chips", "price": 1.00},
{"name": "chocolate", "price": 1.50},
{"name": "gummy bears", "price": 2.20},
{"name": "water", "price": 0.55},
{"name": "juice", "price": 1.30}
]
MIN_ITEM = 1
MAX_ITEM = len(items)
CURRENCY = "£"
def clear_screen():
os.system("cls" if os.name == "nt" else "clear")
def highlight_text(text):
return f"\033[30;102m {text} \033[0m"
while True:
clear_screen()
print(
"Welcome to the Vending Machine!",
"Items Available:",
"----------------",
sep="\n"
)
for i, item in enumerate(items, 1):
print(f"{i}. {item["name"].capitalize()} - {CURRENCY}{item["price"]:.2f}")
choice = 0
while True:
try:
choice = int(input(f"Please select between {MIN_ITEM}-{MAX_ITEM}: ")) - 1
if 0 <= choice < len(items):
break
else:
raise ValueError
except ValueError:
# Move the cursor back to the previous line and clear it
sys.stdout.write("\033[A\033[K")
sys.stdout.flush()
current_balance = money = 0
price = items[choice]["price"]
while True:
clear_screen()
print(f"You selected {highlight_text(items[choice]["name"])} which costs {CURRENCY}{price:.2f}")
try:
money = input(f"Current balance: {CURRENCY}{current_balance:.2f}\nPlease insert your money: ")
if money.lower() in ["q", "quit"]:
clear_screen()
print("Transaction cancelled. Get your money up.")
time.sleep(4)
break
current_balance += float(money)
if current_balance >= price:
clear_screen()
print(
f" You just bought: {highlight_text(items[choice]["name"])}",
f" Price: {CURRENCY}{price:.2f}",
f" Current balance: {CURRENCY}{current_balance:.2f}",
f"Here is your change: {CURRENCY}{(current_balance - price):.2f}",
sep="\n"
)
thanks = "Thank you for your purchase."
print(
f"\n{"-"*len(thanks)}",
f"\n{thanks}",
sep=""
)
time.sleep(8)
break
except ValueError:
money = 0