You need to enable JavaScript to run this app. Python循环中如何累加计算多套餐订单的总消费金额?
优惠活动
大模型
产品
解决方案
定价
更多

Python循环中如何累加计算多套餐订单的总消费金额?

需新增/修改的代码说明

  1. 先修复原有代码的逻辑错误:原判断语句combo != 'x' and 'X'、combo == 'a' and 'A'写法不符合Python逻辑,无法正确识别大小写输入,甚至会导致输入X后无法正常退出循环,统一用.lower()方法转小写后判断即可解决。
  2. 新增总价累加逻辑:
    • 循环执行前初始化一个总金额变量,初始值设为0
    • 每次计算完单种套餐的订单价格后,把该价格加到总金额变量中
    • 循环结束后输出总金额即可

修改后的完整代码

# 新增:初始化总金额变量
total_price = 0
combo = str(input('Enter Combo Type (A/B/C or X to end) ='))

# 修正while判断逻辑,转小写后判断
while combo.lower() != 'x':
    if combo.lower() == 'a':
        qtt = int(input('How many do you want to order  ='))
        price = qtt * 40
        # 新增:累加当前套餐价格到总金额
        total_price += price
        print('Order price for combo A =', price)
        combo = str(input('Enter Combo Type (A/B/C or X to end) ='))
    elif combo.lower() == 'b':
        qtt = int(input('How many do you want to order  ='))
        price = qtt * 52
        total_price += price
        print('Order price for combo B =', price)
        combo = str(input('Enter Combo Type (A/B/C or X to end) ='))
    elif combo.lower() == 'c':
        qtt = int(input('How many do you want to order  ='))
        price = qtt * 46
        total_price += price
        print('Order price for combo C =', price)
        combo = str(input('Enter Combo Type (A/B/C or X to end) ='))
    else:
        print("Wrong input, please try again.")
        combo = str(input('Enter Combo Type (A/B/C or X to end) ='))

# 新增:循环结束后输出总金额
print('Total order price for all combos =', total_price)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 14:36:04