1. 使用内置函数 `sum()`:
numbers = [1, 2, 3, 4, 5]total = sum(numbers)print(f"总和为:{total}")
2. 使用 `for` 循环:
numbers = [1, 2, 3, 4, 5]total = 0for num in numbers:total += numprint(f"总和为:{total}")
3. 使用递归函数:
def calculate_sum(numbers):if not numbers:return 0else:return numbers + calculate_sum(numbers[1:])numbers = [1, 2, 3, 4, 5]total = calculate_sum(numbers)print(f"总和为:{total}")

4. 使用 `numpy` 库中的 `sum()` 函数(适用于多维数组):
import numpy as npnumbers = np.array([[1, 2, 3], [4, 5, 5]])total = np.sum(numbers)print(f"总和为:{total}")
5. 计算整数各个数字之和:
def sum_digits(num):total = 0while num > 0:total += num % 10num //= 10return totaln = 12345print(f"数字 {n} 的各位数字之和为:{sum_digits(n)}")
以上是计算数字总和的几种常见方法。选择哪种方法取决于你的具体需求以及你正在处理的数据类型
