python

python中序列求和的方法是什么

小亿
115
2024-05-13 10:06:52
栏目: 编程语言

在Python中,可以使用内置的sum()函数来对序列进行求和。sum()函数可以接受一个序列作为参数,并返回序列中所有元素的和。示例如下:

numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total)  # 输出:15

除了使用sum()函数外,还可以使用循环来对序列进行求和,示例如下:

numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
    total += num
print(total)  # 输出:15

总的来说,sum()函数是Python中求和的一种简便方法,能够快速对序列中的元素进行求和。

0
看了该问题的人还看了