写一条自动售货机的Python代码
时间: 2023-11-21 15:06:20 浏览: 84
好的,以下是一个简单的自动售货机的Python代码:
```
products = {"A": {"name": "可乐", "price": 3},
"B": {"name": "矿泉水", "price": 2},
"C": {"name": "雪碧", "price": 3.5}}
money = 0
selected_product = ""
while True:
print("可选商品:")
for key, value in products.items():
print(key + ":" + value["name"] + ",价格:" + str(value["price"]) + "元")
selected_product = input("请输入您选择的商品编号(A、B或C),或输入0退出:")
if selected_product == "0":
print("退出成功!")
break
elif selected_product not in products.keys():
print("非法输入,请输入A、B或C!")
continue
selected_price = products[selected_product]["price"]
print("您选择的商品为:" + products[selected_product]["name"] + ",价格为" + str(selected_price) + "元")
while True:
money_input = input("请输入投入的钱数(可以按q键退出):")
if money_input == "q":
print("退出成功!")
break
elif not money_input.isdigit():
print("非法输入,请重新输入:")
continue
money += float(money_input)
if money < selected_price:
print("请继续投入,剩余:" + str(selected_price - money) + "元")
continue
else:
change = money - selected_price
print("购买成功!找零:" + str(change) + "元")
money = 0
break
```
这个代码可以让用户选择购买的商品,投入相应的钱数,然后给出找零。如果需要退出,可以输入0或按q键。
阅读全文