Python杂货店商品价格关联展示及用户交互功能开发问询
Hey there! Let's build out that user interaction functionality for your Python grocery store program. You've already got a solid foundation with your item list and initial budget—now let's add the ability for users to browse, buy items, check their remaining money, and exit when they're done.
Step 1: Improve Item Display (Show Prices!)
First, let's update your item printout to include both the item name and price, plus a numbered index so users can easily select what they want to buy. This makes the interface much clearer:
items = [('Diapers', 10), ('Peanut Butter', 5), ('Butter', 6), ('Cheese', 3), ('Milk', 3.5), ('Yogurt', 1.99), ('Eggs', 4.5), ('Bread', 4), ('Shrimp', 2.5), ('Coffee', 1.5)] totalmoney = 50 # Print initial budget and formatted item list print(f'You have ${totalmoney:.2f} dollars!') print('These are your options:\n') for idx, (item_name, item_price) in enumerate(items, start=1): print(f'{idx}. {item_name} - ${item_price:.2f}')
Step 2: Add User Interaction Loop
Next, we'll add a continuous loop that lets users choose actions (buy items, check budget, quit) until they decide to exit. We'll also handle edge cases like invalid inputs or insufficient funds:
while True: # Display action menu print('\n--- What would you like to do? ---') print('1. Buy an item') print('2. Check remaining budget') print('3. Quit shopping') # Get user input user_choice = input('Enter your choice (1/2/3): ') # Handle buying an item if user_choice == '1': try: item_number = int(input('Enter the number of the item you want to buy: ')) # Validate the item number is within range if 1 <= item_number <= len(items): selected_item, item_cost = items[item_number - 1] # Check if user can afford the item if item_cost <= totalmoney: totalmoney -= item_cost print(f'✅ You bought {selected_item}! Remaining budget: ${totalmoney:.2f}') else: needed = item_cost - totalmoney print(f'❌ Sorry, you can\'t afford {selected_item}. You need ${needed:.2f} more.') else: print(f'Please enter a number between 1 and {len(items)}.') except ValueError: print('Please enter a valid number for the item.') # Handle checking remaining budget elif user_choice == '2': print(f'💰 Remaining budget: ${totalmoney:.2f}') # Handle quitting the program elif user_choice == '3': print('Thanks for shopping with us! Have a great day!') break # Handle invalid menu choices else: print('Invalid choice. Please enter 1, 2, or 3.')
Key Features Explained
- Numbered Items: Using
enumerate(items, start=1)gives each item a user-friendly number (starting at 1 instead of 0, which is more intuitive for people). - Budget Tracking: We update
totalmoneyevery time a user buys an item, and always check if they have enough funds first. - Error Handling: The
try/exceptblock catches cases where users enter non-numeric values, so the program doesn't crash. - Clear Feedback: Emojis and formatted messages make it easy for users to understand what's happening (success, insufficient funds, invalid input).
You can tweak this further—for example, adding a "view cart" feature if you want users to track what they've bought, or allowing multiple quantities of an item. But this gives you a fully functional interactive base!
内容的提问来源于stack exchange,提问作者Jay Goldston

