Python中while循环启停问题求助:杂货清单程序开发
Grocery List Program: Complete Implementation with Fixes
Hey Mike, let's get your grocery list program working properly. I'll put together a full solution that handles product selection, separate tax/deposit tracking, a clean exit option, and fixes the while loop control issue you mentioned. First, let's recap the requirements to make sure we cover everything:
- Let users select multiple products from a predefined list
- Calculate subtotal, separate tax, separate deposit (like for bottles), and grand total
- Include an option to exit the program and print the final bill
- Fix while loop start/stop logic to avoid infinite loops or early termination
Issues in Your Existing Code Snippet
Looking at the partial code you shared:
#Welcome user to user display product and prices print("Hello, welcome to the store") print("This is the list & products") print("0,M...
Here are the immediate problems:
- Incomplete product list: The third print statement cuts off, so users can't see all available items and their prices.
- No loop structure: There's no while loop to handle repeated product selection—right now it just prints a welcome message and stops.
- No tracking variables: No variables to store subtotal, tax, deposit, or total amounts.
- No exit mechanism: No way for the user to signal they're done selecting items.
Working Solution Code
Here's a complete, tested implementation that addresses all your needs:
# Define product list with name, price, tax rate, and deposit (if applicable) products = [ {"id": 1, "name": "Milk", "price": 3.99, "tax_rate": 0.08, "deposit": 0.10}, {"id": 2, "name": "Bread", "price": 2.49, "tax_rate": 0.08, "deposit": 0.00}, {"id": 3, "name": "Eggs", "price": 4.79, "tax_rate": 0.08, "deposit": 0.00}, {"id": 4, "name": "Soda Bottle", "price": 1.99, "tax_rate": 0.08, "deposit": 0.15}, {"id": 0, "name": "Exit & View Total", "price": 0.00, "tax_rate": 0.00, "deposit": 0.00} ] # Initialize tracking variables subtotal = 0.0 total_tax = 0.0 total_deposit = 0.0 # Welcome message print("Hello, welcome to the store!") print("\nHere's our product list:") # Print formatted product list for item in products: print(f"{item['id']}. {item['name']} - ${item['price']:.2f} (Deposit: ${item['deposit']:.2f})") # Main selection loop while True: try: selection = int(input("\nEnter the ID of the product you want to add (or 0 to exit): ")) # Find the selected product selected_item = next((item for item in products if item['id'] == selection), None) if not selected_item: print("Invalid ID! Please choose from the list above.") continue # Handle exit option if selection == 0: break # Calculate item's tax and add to totals item_tax = selected_item['price'] * selected_item['tax_rate'] subtotal += selected_item['price'] total_tax += item_tax total_deposit += selected_item['deposit'] print(f"Added {selected_item['name']} to your list!") except ValueError: print("Please enter a valid number for the product ID.") # Calculate grand total grand_total = subtotal + total_tax + total_deposit # Print final bill print("\n--- Final Bill ---") print(f"Subtotal: ${subtotal:.2f}") print(f"Total Tax: ${total_tax:.2f}") print(f"Total Deposit: ${total_deposit:.2f}") print(f"Grand Total: ${grand_total:.2f}") print("Thank you for shopping with us!")
Key Features Explained
- Controlled While Loop: We use
while Truewith abreakstatement when the user selects ID 0. This ensures the loop runs until the user explicitly chooses to exit—no infinite loops or unexpected stops. - Separate Tax/Deposit Tracking: Each product has its own tax rate and deposit value, so we can calculate and display these separately just like a real store bill.
- Error Handling: The
try-exceptblock catches non-numeric inputs, so the program doesn't crash if the user enters something other than a number. - Clear Product Display: The product list is formatted neatly so users can easily see each item's price and deposit.
How This Fixes Your Original Issues
- Loop Control: The
while Trueloop with a conditionalbreaksolves the start/stop problem—you start the loop automatically, and it only ends when the user selects exit. - Billing Logic: We added variables to track subtotal, tax, and deposit separately, then compute the grand total correctly.
- Complete Structure: The code includes a product list, user input handling, error checking, and a final bill output—all missing from your original snippet.
内容的提问来源于stack exchange,提问作者Mike Doc Levine
相关产品推荐
相关产品推荐

