Python sum()函数
在 Python 中,sum()
函数用于对给定的可迭代对象进行求和操作。
sum()函数语法
sum(iterable, start=0)
其中:
iterable
参数是可迭代对象,可以是列表、元组、集合等等;start
参数是起始值,如果省略则默认为0
。
sum()
函数对可迭代对象中的所有元素进行求和,并返回求和结果。
如果可迭代对象中包含非数值类型的元素,则会抛出TypeError
异常。
sum()函数示例
下面是一些示例:
# 对列表进行求和
lst = [1, 2, 3, 4, 5]
s = sum(lst)
print(s) # 输出 15
s = sum(lst,100) #指定起始值
print(s) # 输出 115