You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python自动贩卖机代码报错:'<' not supported between instances of 'dict' and 'int' 问题修复咨询

解决自动贩卖机的TypeError问题及逻辑修正

Hey there! No worries about grammar at all—we've all been there as new programmers, especially when juggling code and a second language. Let's break down what's going wrong and fix your vending machine step by step.

核心错误原因

The TypeError happens because you're trying to compare a dictionary (inv_coins) with an integer (price). Looking at your code, you defined inv_coins as a dict that tracks the machine's change stock (like {100:0, 50:0, ...}), but then you tried using it to track the total money the user inserted. That's a classic variable mix-up!

You need two separate variables here:

  • One to track the user's deposited amount (a number, not a dict)
  • Another to track the machine's coin inventory (the dict with counts of each bill/coin)

关键修改步骤

Let's go through the fixes one by one:

  1. Split the variables

    • Rename your coin inventory dict to something clear like coin_inventory (you had cim which is hard to read)
    • Add a new variable user_deposit = 0 to track how much money the user has put in
  2. Fix the deposit loop
    Replace while inv_coins < price: with while user_deposit < price:—this compares the user's total deposit (a number) to the item price (another number, which works!)

  3. Implement proper change calculation
    After the user pays enough, calculate the change, then use the machine's coin inventory to give back the correct bills/coins (starting from largest to smallest for efficiency).

  4. Fix other small bugs

    • The show() function was modifying the original items list while iterating, which causes skipped items. Instead, filter out out-of-stock items without altering the original list.
    • Add basic input validation for money deposits (to avoid crashes if someone enters non-numeric values)
    • Fix the change refund logic—check if change > 0 instead of comparing a dict to 0

修改后的完整代码

def vend():
    # Define items with clear structure
    items = [
        {'item': 'Chips', 'price': 11, 'stock': 50},
        {'item': 'Water', 'price': 7, 'stock': 50},
        {'item': 'Candies', 'price': 8, 'stock': 50},
        {'item': 'Sandwich', 'price': 27, 'stock': 50}
    ]
    # Machine's coin inventory: {denomination: count}
    coin_inventory = {100: 0, 50: 0, 10: 20, 5: 20, 2: 20, 1: 20}
    
    print('Hi there! This is the vending machine of Felix Seletskiy \n@@@@@@@@@@@@@@@')

    def show(items):
        print('\nitems available \n***************')
        # Filter out out-of-stock items without modifying the original list
        available_items = [item for item in items if item['stock'] > 0]
        for item in available_items:
            print(f"{item['item']} - ${item['price']}")
        print('***************\n')

    continue_to_buy = True
    user_deposit = 0  # Track user's total deposited money

    while continue_to_buy:
        show(items)
        selected_name = input('Select item: ').strip()
        selected_item = None
        
        # Find the selected item
        for item in items:
            if item['item'].lower() == selected_name.lower():
                selected_item = item
                break
        
        if not selected_item or selected_item['stock'] == 0:
            print("Sorry, that item isn't available.")
            continue
        
        price = selected_item['price']
        # Handle user deposit
        while user_deposit < price:
            try:
                amount = float(input(f"Insert ${price - user_deposit} more: "))
                # Only accept positive amounts (basic validation)
                if amount <= 0:
                    print("Please insert a positive amount.")
                    continue
                user_deposit += amount
            except ValueError:
                print("Please enter a valid number.")
        
        # Dispense the item
        print(f"You got {selected_item['item']}!")
        selected_item['stock'] -= 1
        
        # Calculate and give change
        change = user_deposit - price
        user_deposit = 0  # Reset deposit for next purchase
        
        if change > 0:
            refund = {}
            # Sort denominations from largest to smallest for optimal change
            for denom in sorted(coin_inventory.keys(), reverse=True):
                if change >= denom and coin_inventory[denom] > 0:
                    count = min(int(change // denom), coin_inventory[denom])
                    refund[denom] = count
                    change -= denom * count
                    coin_inventory[denom] -= count
            
            if change == 0:
                print(f"Refunded: {refund}")
            else:
                print("Sorry, we can't give you full change. Please take your money back.")
                # If we can't give full change, return the user's deposit
                user_deposit = price + change
        
        # Ask if user wants to buy more
        another = input("Buy something else? (y/n): ").strip().lower()
        if another == 'n':
            continue_to_buy = False
            print('Thank you, have a nice day!\n')

vend()

额外说明

  • The code uses try/except to handle invalid input (like someone typing letters instead of numbers)
  • Change is calculated using the largest denominations first, which is standard for vending machines
  • The show() function now uses a list comprehension to filter out-of-stock items without breaking the original list
  • Variable names follow PEP8 style (like continue_to_buy instead of continueToBuy) for better readability

内容的提问来源于stack exchange,提问作者SoftwareTurtle

火山引擎 最新活动