Python如何在while循环中保留订单数据实现团体点餐汇总输出
团体点餐订单累积与汇总输出解决方案
问题分析
原代码存在两个核心问题:
- 每次循环通过
bottles = [int(howmany) for _ in range(howmany)]重置列表,无法累积多人的订单数据 - 每次循环直接计算并打印当前订单的总价,无法实现循环结束后统一汇总所有订单
修改后的代码
# 初始化团体订单列表,用于存储所有成员的订单详情 group_orders = [] tax_rate = 0.06 # 定义每个选项对应的单价,简化后续计算逻辑 item_prices = { '1': 0.99, '2': 0.79, '3': 1.09 } while True: option = input('请选择餐品选项(1/2/3): ') # 验证选项有效性,避免无效输入导致错误 if option not in item_prices: print('无效选项,请选择1、2或3') continue howmany = int(input('请输入购买数量: ')) # 将当前成员的订单信息存入团体订单列表,实现数据累积 group_orders.append({ 'option': option, 'quantity': howmany }) quit_option = input('是否继续添加订单?输入yes继续,输入quit结束: ') if quit_option == 'quit': break elif quit_option != 'yes': print('输入无效,默认继续添加订单') # 循环结束后,统一计算所有订单的总价 subtotal = 0.0 # 先计算税前总价 for order in group_orders: price_per_item = item_prices[order['option']] subtotal += order['quantity'] * price_per_item # 计算含税后的最终总价 total = subtotal * (1 + tax_rate) # 输出汇总结果 print('--- 团体订单汇总 ---') for idx, order in enumerate(group_orders, 1): item_price = item_prices[order['option']] print(f"成员{idx}: 选项{order['option']},数量{order['quantity']},小计: ${order['quantity'] * item_price:.2f}") print(f"订单税前总价: ${subtotal:.2f}") print(f"税率6%,最终总价: ${total:.2f}") print('感谢您的点餐,我们会尽快准备!')
关键改动说明
- 用
group_orders列表存储每个成员的订单详情(选项+数量),彻底解决每次循环重置数据的问题,实现订单累积 - 将餐品单价存入字典
item_prices,消除原代码的重复逻辑,后续调整价格只需修改字典即可 - 把退出判断整合到循环内部,确保每完成一个成员的订单后,都能选择继续或结束点餐
- 移除循环内的即时打印逻辑,改为循环结束后统一计算并输出所有订单的详细汇总和最终总价
- 增加输入验证,避免无效选项导致程序出错
内容的提问来源于stack exchange,提问作者jones007
相关产品推荐
相关产品推荐

