在Python中计算数字总和,你可以使用以下几种方法:
1. 使用内置函数 `sum()`:
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(f"总和为:{total}")
2. 使用 `for` 循环:
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
print(f"总和为:{total}")
3. 使用递归函数:
def calculate_sum(numbers):
if not numbers:
return 0
else:
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 np
numbers = np.array([[1, 2, 3], [4, 5, 5]])
total = np.sum(numbers)
print(f"总和为:{total}")
def sum_digits(num):
total = 0
while num > 0:
total += num % 10
num //= 10
return total
n = 12345
print(f"数字 {n} 的各位数字之和为:{sum_digits(n)}")