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

Python购物程序如何按指定格式输出商品明细及总价

购物程序结算页格式化输出实现方案

需求说明

开发购物程序时,用户结束购物需要按固定格式展示所有已录入购物数据,目标格式如下:

PRODUCT CODE - QUANTITY   -  PRICE
    apple    -    2       -  10.64
   coconut   -    3       -  19.35
   orange    -    1       -  6.45
                      TOTAL: 36.44

现有代码仅实现了总价求和功能,未做商品聚合、格式对齐,且存在输入END后未跳出循环的问题,原有代码如下:

product_list = ['apple', 'orange', 'watermelon', 'banana', 'coconut']
price_list = [ 5.32 , 6.45 , 2.37 , 5.32, 6.45 ]

bought_product_list = [ ]
bought_price_list = [ ]
quantity = 0

while True:

        
    product_code = input('Enter the product code or END to finnish shopping: ')
    print(' ')

    

    if product_code in product_list:
        product_code_idx = product_list.index(product_code)
        product_price = price_list[product_code_idx]
        
        quantity = int(input('Enter the quantity:'))
            
        bought_product_list.extend([product_code] * quantity)
        bought_price_list.extend([product_price] * quantity)
    

    if product_code == 'END':
        print(' ')
        print('TOTAL: ',sum(bought_price_list))

改造思路

  • 替换原有按单个商品拆分存储的列表结构,改用字典存储已购商品,键为商品编码,值存储对应购买数量、单价,避免重复录入同个商品时生成冗余数据,也方便后续聚合计算
  • 结算输出时用固定宽度字符串格式化实现三列对齐,商品名、数量列居中,小计金额列右对齐并保留2位小数
  • 总价计算完成后,调整缩进对齐到示例要求的位置,同样保留2位小数
  • 补全END分支的循环退出逻辑,避免死循环

修正后完整代码

product_list = ['apple', 'orange', 'watermelon', 'banana', 'coconut']
price_list = [5.32, 6.45, 2.37, 5.32, 6.45]

# 已购商品存储结构:{商品名称: [购买数量, 商品单价]}
bought_product = {}

while True:
    product_code = input('Enter the product code or END to finish shopping: ')
    print(' ')
    
    # 输入END直接退出录入循环
    if product_code == 'END':
        break
    
    if product_code in product_list:
        product_idx = product_list.index(product_code)
        unit_price = price_list[product_idx]
        buy_quantity = int(input('Enter the quantity:'))
        # 同个商品重复录入时累加数量,否则新增记录
        if product_code in bought_product:
            bought_product[product_code][0] += buy_quantity
        else:
            bought_product[product_code] = [buy_quantity, unit_price]

# 按要求格式打印结算单
total_amount = 0
# 打印表头
print(f"{'PRODUCT CODE':^12} - {'QUANTITY':^8} -  PRICE")
for name, (qty, price) in bought_product.items():
    sub_total = qty * price
    total_amount += sub_total
    # 逐行打印商品记录,固定宽度对齐
    print(f"{name:^12} - {qty:^8} -  {sub_total:>6.2f}")
# 打印对齐后的总价
print(f"{'TOTAL: ' + f'{total_amount:.2f}':>34}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 18:27:32