Python杂货店购物程序:实现购物车已购商品退回功能求助
Adding Return Functionality to Your Grocery Shopping Program
Hey there! Let's get that return feature working for your Python grocery app. I'll walk you through modifying your code step by step, with clear explanations for each part.
First, let's fix up the core flow and add the missing logic for both buy and return actions. Here's the updated code with full functionality:
# Define available items and their prices (converted to a dictionary for easy lookup) items = [('diapers', 10.00), ('peanuts', 5.00), ('butter', 6.25), ('cheese', 3.00), ('milk', 3.5), ('yogurt', 1.99), ('eggs', 4.5), ('bread', 4), ('shrimp', 2.5), ('coffee', 1.5)] item_prices = dict(items) # Lets us quickly get a price by item name money = 50.0 cart_list = [] # Renamed for PEP8 style consistency valid_actions = ('buy', 'return', 'quit') while True: # Print formatted item menu print("\nAvailable Items:") for name, price in items: print(f"{name.capitalize()} .... ${price:.2f}") # Get user's action choice action = input("\nChoose an action (buy/return/quit): ").lower() if action == 'quit': print(f"\nThanks for shopping! You have ${money:.2f} left.") break elif action == 'buy': # Handle item purchase item_name = input("Enter the name of the item to buy: ").lower() if item_name in item_prices: price = item_prices[item_name] if money >= price: cart_list.append(item_name) money -= price print(f"Added {item_name} to cart! You have ${money:.2f} left.") else: print(f"Sorry, you don't have enough money for {item_name}.") else: print(f"Sorry, {item_name} isn't available.") elif action == 'return': # Handle item return if not cart_list: print("Your cart is empty—nothing to return!") continue # Show current cart contents print("\nYour cart contains:") for idx, item in enumerate(cart_list, 1): print(f"{idx}. {item.capitalize()}") # Get item to return return_item = input("Enter the name of the item to return: ").lower() if return_item in cart_list: price = item_prices[return_item] cart_list.remove(return_item) money += price print(f"Returned {return_item}! You have ${money:.2f} now.") else: print(f"Sorry, {return_item} isn't in your cart.") else: print("Invalid action! Please choose 'buy', 'return', or 'quit'.")
Key Changes & Explanations:
- Item Price Dictionary: Converted
itemstoitem_pricesdictionary so we can instantly look up any item's price by name—this simplifies both buy and return logic a lot. - Action Input Handling: Added clear prompts for the user to select their action, plus handling for invalid inputs so the app doesn't break if someone types something wrong.
- Complete Buy Flow: Filled in the missing purchase logic—checks if the item exists, if the user has enough money, then adds the item to the cart and deducts the price from
money. - Return Logic Breakdown:
- First checks if the cart is empty (no point in trying to return nothing!)
- Shows the user their current cart contents so they know what they can return
- Verifies the requested item is in the cart, then removes it and adds the price back to
money
- Readability Tweaks: Used
:.2fto display money with 2 decimal places, and capitalized item names in menus for cleaner output.
Optional Upgrade: Track Item Quantities
If you want to handle multiple of the same item (instead of having duplicate entries in cart_list), switch to a dictionary for the cart. Here's a quick snippet of how that would work:
cart_dict = {} # Keys: item names, Values: quantities # When buying: if item_name in item_prices: price = item_prices[item_name] if money >= price: cart_dict[item_name] = cart_dict.get(item_name, 0) + 1 money -= price # ... rest of logic # When returning: if return_item in cart_dict and cart_dict[return_item] > 0: price = item_prices[return_item] cart_dict[return_item] -= 1 if cart_dict[return_item] == 0: del cart_dict[return_item] money += price # ... rest of logic
This way, if the user buys 3 diapers, they can return 1 or all 3 without cluttering the cart with duplicate entries.
内容的提问来源于stack exchange,提问作者Jay Goldston
相关产品推荐
相关产品推荐

