Python循环中如何累加计算多套餐订单的总消费金额?
需新增/修改的代码说明
- 先修复原有代码的逻辑错误:原判断语句
combo != 'x' and 'X'、combo == 'a' and 'A'写法不符合Python逻辑,无法正确识别大小写输入,甚至会导致输入X后无法正常退出循环,统一用.lower()方法转小写后判断即可解决。 - 新增总价累加逻辑:
- 循环执行前初始化一个总金额变量,初始值设为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
相关产品推荐
相关产品推荐

