You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3中如何将输入与字典元素匹配?新手购物清单实现求助

Fixing Your Shopping List Program

Hey there! Let's work through this shopping list problem step by step. I see you're stuck on matching input items to their prices in the dictionary, plus there are a few syntax and logic gaps we can iron out to get this working right.

First, Let's Fix Syntax & Naming Issues

First off, a couple quick fixes to avoid Python errors:

  • Don't use list as a variable name—it's a built-in Python type! Let's rename that to item_prices instead.
  • If needs to be lowercase (if) in Python (case matters here!).
  • Your input() call is missing a closing parenthesis—easy typo to fix!
  • sum is also a built-in function, so let's use total_cost for our running total to avoid confusion.
  • You'll need to define a budget value (since your logic references it) and initialize total_cost to 0 at the start.

Matching Items to Their Prices

The key part you're missing: to get the price of the item the user inputs, you just use item_prices[buy]—this looks up the value (price) associated with the key (item name) in your dictionary. Super straightforward once you know the syntax!

Updated Working Code

Here's a revised version of your function that puts it all together, with comments explaining each step:

def shoplist():
    # Define your item prices (renamed from "list" to avoid conflict)
    item_prices = {"apple": 30, "orange": 20, "milk": 60}
    # Set your budget (you can change this to any number that makes sense)
    budget = 100
    # Initialize total cost to 0 before we start adding items
    total_cost = 0

    while total_cost <= budget:
        # Get user input, with the missing closing parenthesis added
        buy = str(input("What do you want to purchase? (Type 'quit' to stop early) "))
        
        # Let the user exit early if they're done shopping
        if buy.lower() == "quit":
            break
        
        # Check if the item exists in our price dictionary
        if buy in item_prices:
            # Grab the item's price and add it to the total (this is the matching step you needed!)
            item_price = item_prices[buy]
            total_cost += item_price
            print(f"Added {buy} for {item_price}. Total so far: {total_cost}")
        else:
            print(f"Sorry, we don't have {buy} in our inventory.")
    
    # Once we exit the loop, explain why to the user
    if total_cost > budget:
        print(f"Whoa, your total ({total_cost}) is over your budget of {budget}! Stopping here.")
    else:
        print(f"Thanks for shopping! Your final total is {total_cost}.")

# Call the function to run the program
shoplist()

Key Improvements Explained

  • Added an early quit option so the user can stop shopping before hitting the budget.
  • Prints the running total every time an item is added, so the user can track their spending.
  • Gives a clear message if the user inputs an item that isn't in the dictionary, instead of crashing.
  • The loop stops immediately once adding an item would push the total over budget, which aligns with your original goal.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:35:13