帮我用python写一个自动售货机的代码
当然可以帮你写一个自动售货机的代码。以下是一个简单的自动售货机的代码示例:
class VendingMachine:
    def __init__(self):
        self.products = {
            'Coke': 10,
            'Sprite': 8,
            'Water': 5
        }
        self.balance = 0
    
    def insert_coin(self, amount):
        self.balance += amount
    
    def select_product(self, product):
        if product in self.products:
            price = self.products[product]
            if self.balance >= price:
                self.balance -= price
                self.products[product] -= 1
                print(f"Here is your {product}.")
            else:
                print("Insufficient balance. Please insert more coins.")
        else:
            print("Product not found.")
    
    def check_balance(self):
        return self.balance
    
    def check_stock(self):
        return self.products
# 测试代码
vending_machine = VendingMachine()
vending_machine.insert_coin(10)
vending_machine.select_product('Coke')
print(vending_machine.check_balance())  # 输出: 0
print(vending_machine.check_stock())  # 输出: {'Coke': 9, 'Sprite': 8, 'Water': 5}
这是一个简单的自动售货机类,具有插入硬币、选择产品、查询余额和库存等功能。你可以根据实际需求进行修改和扩展。
原文地址: https://www.cveoy.top/t/topic/i3XG 著作权归作者所有。请勿转载和采集!