英文文檔:
sum(iterable[, start])
Sums start and the items of an iterable from left to right and returns the total. start defaults to 0. The iterable‘s items are normally numbers, and the start value is not allowed to be a string.
說明:
1. 函數功能是對可迭代類型進行求和。要求:① 接收對象是可迭代類型。② 可迭代對象所有元素類型是數值型。
# 傳入可迭代對象 >>> sum((1,2,3,4)) 10 >>> sum([1,2,3,4]) 10 >>> sum(range(10)) 45 # 元素類型必須是數值型 >>> sum((1.5,2.5,3.5,4.5)) 12.0 >>> sum((complex(1,-1),complex(2,-2))) (3-3j) >>> sum((1,2,3,'4')) Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> sum((1,2,3,'4')) TypeError: unsupported operand type(s) for +: 'int' and 'str'
2. 可以傳入一個可選參數start,表示求和前的初始化值,如果傳入空的可迭代數據類型,則返回初始值。
>>> sum((1,2,3,4),2) 12 >>> sum((1,2,3,4),-10) 0 # 傳入空可迭代對象,直接返回初始值 >>> sum([],2) 2
