饮品自动售货机python代码
时间: 2023-11-08 09:04:58 浏览: 150
Python实现的一个自动售饮料程序代码分享
饮品自动售货机的Python代码可以如下所示:
```python
class VendingMachine:
def __init__(self):
self.products = {
'Coke': 10,
'Pepsi': 8,
'Sprite': 5
}
self.prices = {
'Coke': 2.5,
'Pepsi': 2.0,
'Sprite': 1.5
}
self.balance = 0.0
def display_products(self):
for product, quantity in self.products.items():
print(f'{product}: {quantity}')
def insert_coin(self, amount):
self.balance += amount
def purchase(self, product):
if product not in self.products:
print("Invalid product!")
return
if self.products[product] == 0:
print("Out of stock!")
return
if self.balance < self.prices[product]:
print("Insufficient balance!")
return
self.products[product] -= 1
self.balance -= self.prices[product]
print(f"Purchased {product} successfully!")
def get_change(self):
change = self.balance
self.balance = 0.0
return change
# 示例使用
vending_machine = VendingMachine()
vending_machine.display_products()
vending_machine.insert_coin(5.0)
vending_machine.purchase('Coke')
change = vending_machine.get_change()
print(f"Change: {change}")
```
阅读全文