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
listas a variable name—it's a built-in Python type! Let's rename that toitem_pricesinstead. Ifneeds to be lowercase (if) in Python (case matters here!).- Your
input()call is missing a closing parenthesis—easy typo to fix! sumis also a built-in function, so let's usetotal_costfor our running total to avoid confusion.- You'll need to define a
budgetvalue (since your logic references it) and initializetotal_costto 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
相关产品推荐
相关产品推荐

