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

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:

  1. Incomplete product list: The third print statement cuts off, so users can't see all available items and their prices.
  2. No loop structure: There's no while loop to handle repeated product selection—right now it just prints a welcome message and stops.
  3. No tracking variables: No variables to store subtotal, tax, deposit, or total amounts.
  4. 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

  1. Controlled While Loop: We use while True with a break statement when the user selects ID 0. This ensures the loop runs until the user explicitly chooses to exit—no infinite loops or unexpected stops.
  2. 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.
  3. Error Handling: The try-except block catches non-numeric inputs, so the program doesn't crash if the user enters something other than a number.
  4. 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 True loop with a conditional break solves 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:10:19