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

如何计算列表数字总和?及Python客群费用计算程序问题求解

问题1:如何计算列表中的数字总和?

有两种常用实现方式:

  • 直接使用Python内置的sum()函数,这是最简洁的方式:
    num_list = [1, 2, 3, 4]
    total = sum(num_list)
    print(total)  # 输出10
    
  • 手动循环累加,适合需要自定义累加逻辑的场景:
    num_list = [1, 2, 3, 4]
    total = 0
    for num in num_list:
        total += num
    print(total)  # 输出10
    
问题2:修复程序无法计算总费用的问题

你的代码存在逻辑错误和功能缺失,修复后的完整代码如下:

def main():
    # 用循环简化输入,避免重复冗余代码
    ages = []
    for i in range(8):
        age = int(input(f"Enter the age of guest {i+1}(in years): "))
        ages.append(age)
    # 接收总费用并打印
    total_cost = getCost(ages)
    print(f"Total cost: ${total_cost}")

def getCost(ages):
    total = 0  # 初始化总费用变量
    for age in ages:
        if age <= 2:
            cost = 0
        # 修正条件逻辑:匹配3-12岁区间,原条件age <=3>12逻辑完全错误
        elif 3 <= age <= 12:
            cost = 14
        elif age >= 65:
            cost = 18
        else:
            cost = 23
        print(f"Guest cost: ${cost}")
        total += cost  # 累加单个客人费用到总费用
    return total  # 返回总费用给调用方

main()

修复要点:

  1. 修正条件判断错误:原代码中elif age <= 3>12是无效逻辑,改为3 <= age <=12来对应3到12岁的收费标准。
  2. 添加总费用累加逻辑:在getCost中初始化total变量,每次循环将单个客人的费用累加到total,最后返回总费用。
  3. 简化输入代码:用循环替代重复的8次输入语句,提升代码简洁性和可维护性。
  4. 接收并输出总费用:在main函数中接收getCost返回的总费用,最终打印总费用结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 00:27:20