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

披萨订单收据格式化技术问询:拆分展示与金额对齐

披萨订单收据格式化解决方案

问题说明

我正在解决披萨订单收据的格式化问题,目前遇到两个核心问题:

  • 无法让收据识别订单列表中的每个子列表对应披萨1、披萨2,无法正确获取对应尺寸并展示配料
  • 不知道如何将税费和总金额右对齐,达到整洁的排版效果

当前输出

Your order:
 [['S', 'ONION', 'BACON', 'HAM', 'MUSHROOM'], ['L', 'BACON', 'CHICKEN', 'SAUSAGE', 'GROUND BEEF']]
7.99
8.49
11.99
Tax: $2.79
Total: $24.27

期望输出

pizza 1: S                    7.99 (#just the base price of the pizza)
- onion
- bacon
- ham
- mushroom
Extra topping (S)      0.50
pizza 2: L
- bacon
- chicken
- sausage
- ground beef
Tax:                          2.79
Total:                       24.27

原代码

收据生成函数

def generateReceipt(pizzaOrder):
    cost = 0
    rawTotal=0
    rawTax = 0
    finalCost=0
    totalCost = 0
    if len(pizzaOrder)==0:
        print("You did not order anything")
        exit()
    for pizzas in pizzaOrder:
        if pizzas [0]=="S":
            cost = 7.99
            totalCost+=cost
            print(cost)
            if len(pizzas)>4:
                extraTopping = len(pizzas)-4
                toppingExtra= 0.5 * extraTopping
                totalCost+=toppingExtra
        if pizzas [0]=="M":
            cost = 9.99
            totalCost+=cost
            if len(pizzas)>4:
                extraTopping = len(pizzas)-4
                toppingExtra = 0.75 * extraTopping
                totalCost+=toppingExtra
                print(cost)
        if pizzas [0]=="L":
            cost = 11.99
            totalCost+=cost
            if len(pizzas)>4:
                extraTopping = len(pizzas)-4
                toppingExtra = 1.00 * extraTopping
                totalCost+=toppingExtra
                print(cost)
        if pizzas [0]=="XL":
            cost = 13.99
            totalCost+=cost
            if len(pizzas)>4:
                extraTopping = len(pizzas)-4
                toppingExtra = 1.25 * extraTopping
                totalCost+=toppingExtra
                print(cost)
    rawTax= totalCost*0.13
    rawTotal=totalCost+rawTax
    finalCost = f'${rawTotal:.2f}'
    Tax = f'${rawTax:.2f}'
    print('Tax:',Tax)
    print('Total:',finalCost)

订单主代码

import PizzaReceipt
LIST = ('ONION', 'TOMATO', 'HOT PEPPER', 'GREEN PEPPER', 'MUSHROOM', 'OLIVE', 'SPINACH', 'BROCCOLI', 'PINEAPPLE', 'PEPPERONI', 'HAM', 'BACON', 'GROUND BEEF', 'CHICKEN', 'SAUSAGE')
Yourorder = []
pizzaOrder = []
yourToppings = ()
orderPizza = input("Do you want to order some pizza? ").upper()
orderContinue = "YES".upper()
if orderPizza.upper() == orderPizza.upper() == "Q" or orderPizza.upper() == "NO":
    PizzaReceipt.generateReceipt(pizzaOrder)
    exit()
else:
    while orderContinue.upper() == "YES":
        Yourorder = []
        size = ""
        while size.upper() != "S" and size.upper() != "M" and size.upper() !="L" and size.upper()!="XL":
            size = input("Choose a size: S, M, L, or XL: ").upper()
            Yourorder.append(size)
            yourToppings = ""
        while yourToppings != "X":
            yourToppings = input("Type in one of our toppings to add it to your pizza. To see the list of our toppings, enter\n\"LIST\". When you are done adding toppings, enter \"X\"\n").upper()
            if yourToppings.upper() in LIST:
                print("\nSuccessfully added,",yourToppings)
                Yourorder.append(yourToppings)
            elif yourToppings == "LIST".upper():
                print(LIST)
            elif yourToppings == "X":
                print('Finished ordering pizza')
                print(Yourorder)
            else:
                print("Invalid input")
        orderContinue = input("Do you want to order another pizza? ")
        pizzaOrder.append(Yourorder.copy())
        if orderContinue.upper() == "NO":
            print('Your order: \n',pizzaOrder)
PizzaReceipt.generateReceipt(pizzaOrder)

修改后的代码

优化后的收据生成函数

def generateReceipt(pizzaOrder):
    # 定义尺寸对应的基础价格和额外配料单价,简化逻辑
    size_prices = {"S": 7.99, "M": 9.99, "L": 11.99, "XL": 13.99}
    topping_extras = {"S": 0.5, "M": 0.75, "L": 1.0, "XL": 1.25}
    totalCost = 0

    if len(pizzaOrder) == 0:
        print("You did not order anything")
        return

    # 遍历订单,用enumerate获取披萨序号
    for idx, pizza in enumerate(pizzaOrder):
        size = pizza[0]
        base_price = size_prices[size]
        totalCost += base_price

        # 输出披萨标题,左对齐描述,右对齐价格
        print(f"pizza {idx+1}: {size:<20} {base_price:.2f}")

        # 输出配料列表
        toppings = pizza[1:]
        for topping in toppings:
            print(f"- {topping.lower()}")

        # 计算并输出额外配料费用
        if len(toppings) > 3:  # 基础配料为3个,超出部分额外收费
            extra_count = len(toppings) - 3
            extra_cost = extra_count * topping_extras[size]
            totalCost += extra_cost
            print(f"Extra topping ({size})      {extra_cost:.2f}")

    # 计算税费和总价
    rawTax = totalCost * 0.13
    rawTotal = totalCost + rawTax

    # 右对齐税费和总价,控制宽度保证排版整齐
    print(f"Tax:{'':<15} {rawTax:.2f}")
    print(f"Total:{'':<14} {rawTotal:.2f}")

修正后的订单主代码

import PizzaReceipt
LIST = ('ONION', 'TOMATO', 'HOT PEPPER', 'GREEN PEPPER', 'MUSHROOM', 'OLIVE', 'SPINACH', 'BROCCOLI', 'PINEAPPLE', 'PEPPERONI', 'HAM', 'BACON', 'GROUND BEEF', 'CHICKEN', 'SAUSAGE')
pizzaOrder = []
orderPizza = input("你想要订购披萨吗?").upper()

if orderPizza in ["Q", "NO"]:
    PizzaReceipt.generateReceipt(pizzaOrder)
    exit()

orderContinue = "YES"
while orderContinue.upper() == "YES":
    Yourorder = []
    size = ""
    # 修正尺寸输入逻辑:只有输入有效尺寸才加入列表
    while size not in ["S", "M", "L", "XL"]:
        size = input("选择尺寸:S(小)、M(中)、L(大)、XL(超大):").upper()
        if size not in ["S", "M", "L", "XL"]:
            print("无效尺寸,请重新输入。")
    Yourorder.append(size)

    yourToppings = ""
    while yourToppings != "X":
        yourToppings = input("输入配料名称添加到披萨中。输入\"LIST\"查看所有配料,输入\"X\"结束添加配料\n").upper()
        if yourToppings in LIST:
            print(f"\n已成功添加:{yourToppings}")
            Yourorder.append(yourToppings)
        elif yourToppings == "LIST":
            print(LIST)
        elif yourToppings == "X":
            print('披萨订购完成')
        else:
            print("输入无效,请重新操作。")

    orderContinue = input("你想要再订购一份披萨吗?")
    pizzaOrder.append(Yourorder.copy())
    if orderContinue.upper() == "NO":
        print('你的订单:\n', pizzaOrder)

PizzaReceipt.generateReceipt(pizzaOrder)

关键改动说明

  1. 披萨序号与信息展示:用enumerate遍历订单列表,直接获取披萨序号,同时提取尺寸和配料,分别输出标题和配料列表。
  2. 排版对齐:使用Python的f-string格式化功能,通过:<20实现文本左对齐并固定宽度,配合价格的小数格式化,实现整洁的排版;税费和总价通过填充空格实现右对齐。
  3. 简化价格逻辑:将尺寸对应的基础价格和额外配料单价存入字典,替代重复的if判断,代码更简洁易维护。
  4. 修正输入逻辑:原主代码中尺寸输入错误时会将无效值加入订单列表,现在改为只有输入有效尺寸才加入,避免订单数据错误。
  5. 额外配料计算:明确基础配料数量为3个,计算超出部分的费用并单独输出,逻辑更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 21:25:24