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

Python实现从数据库商品列表计算选中商品总价

Corrected Code for Produce Selection & Total Calculation

Here's the fixed version of your code, addressing syntax errors, input validation, and dynamic item selection:

import sqlite3

# Database setup
connection = sqlite3.connect('seasonalProduce.db')
cursor = connection.cursor()

# Create table if not exists
cursor.execute("""CREATE TABLE IF NOT EXISTS productList (
     productID integer PRIMARY KEY,
     productName text NOT NULL,
     productPrice real
);""")

# Insert product records (ignore duplicates)
productRecords = [(1, "Apples", 4.59),
                  (2, "Grapes", 5.99),
                  (3, "Pumpkin", 3.00),
                  (4, "Strawberries", 2.50),
                  (5, "Leafy Greens", 4.00)]
cursor.executemany("INSERT OR IGNORE INTO productList (productID, productName, productPrice) VALUES(?,?,?);", productRecords)

connection.commit()

# Fetch products and store in a dictionary for quick lookup
cursor.execute("SELECT * FROM productList;")
produce = cursor.fetchall()
produce_dict = {item[0]: (item[1], item[2]) for item in produce}

# Close database connection (no longer needed after fetching data)
connection.close()

# Display available products to the user
print("Available Seasonal Produce:")
for product_id, (name, price) in produce_dict.items():
    print(f"{product_id}. {name} - ${price:.2f} per kg")

# Initialize total to 0
total = 0.0

# Main loop for item selection
while True:
    # Get valid product ID from user
    while True:
        try:
            selected_id = int(input("\nEnter the product ID you want to buy: "))
            if selected_id in produce_dict:
                break
            else:
                valid_ids = ", ".join(map(str, produce_dict.keys()))
                print(f"Invalid ID. Please choose from: {valid_ids}")
        except ValueError:
            print("Invalid input. Please enter a numeric ID.")
    
    # Get valid quantity (kg) from user
    product_name, price_per_kg = produce_dict[selected_id]
    while True:
        try:
            quantity = float(input(f"Enter quantity (kg) for {product_name}: "))
            if quantity > 0:
                break
            else:
                print("Quantity must be a positive number.")
        except ValueError:
            print("Invalid input. Please enter a numeric value.")
    
    # Calculate subtotal and update total
    subtotal = quantity * price_per_kg
    total += subtotal
    print(f"Added {quantity:.2f}kg of {product_name} - ${subtotal:.2f}")
    
    # Ask user if they want to add another item
    while True:
        continue_choice = input("\nAdd another item? (Y/N): ").strip().upper()
        if continue_choice in ["Y", "N"]:
            break
        else:
            print("Please enter 'Y' for yes or 'N' for no.")
    
    if continue_choice == "N":
        break

# Print final total
print(f"\nYour total purchase amount is: ${total:.2f}")

Key Fixes & Improvements:

  • Syntax Corrections: Fixed indentation errors and misplaced try-except blocks.
  • Product Lookup: Converted fetched database records into a dictionary for fast access to product details.
  • Dynamic Item Selection: Removed hardcoded choice1, choice2 variables—now supports adding any number of items.
  • Input Validation: Properly validates product IDs (ensures they exist in the list) and quantities (positive numbers only).
  • Price Calculation: Uses the database-stored price per kg and multiplies by user-input quantity to get accurate subtotals.
  • User Experience: Clear product display, meaningful error messages, and formatted currency output.

内容的提问来源于stack exchange,提问作者Rendevouz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 18:43:15