# Python `sum()`函數
> 原文: [https://thepythonguru.com/python-builtin-functions/sum/](https://thepythonguru.com/python-builtin-functions/sum/)
* * *
于 2020 年 1 月 7 日更新
* * *
`sum()`函數采用一個可迭代的并返回其中的項目總數。
**語法**:
```py
sum(iterable, [start]) -> number
```
| 參數 | 描述 |
| --- | --- |
| `iterable`(必填) | 可迭代項,例如字符串,列表,字典等。 |
| `start`(可選) | 一個可選的數值添加到最終結果中。 默認為`0`。 |
`sum()`函數僅適用于數字值,嘗試將其用于非數字類型將導致錯誤。
這是一個例子:
```py
>>>
>>> sum([1, 2, 3, 4, 5]) # sum values in a list
15
>>>
>>> sum((1, 2, 3, 4, 5)) # sum values in a tuple
15
>>>
>>> sum({1, 2, 3, 4, 5}) # sum values in a set
15
>>>
>>> sum({1: "one", 2: "two", 3: "three"}) # sum values in a
6
>>>
```
試試看:
```py
print(sum([1, 2, 3, 4, 5])) # sum values in a list
print(sum((1, 2, 3, 4, 5))) # sum values in a tuple
print(sum({1, 2, 3, 4, 5})) # sum values in a set
print(sum({1: "one", 2: "two", 3: "three"})) # sum values in a
```
在最后一個命令中,`sum()`將字典中的鍵添加進去,而忽略其值。
這是另一個示例,它指定要添加到最終結果中的`start`值。
```py
>>>
>>> sum([10, 20, 30], 100)
160
>>>
```
試一試:
```py
print(sum([10, 20, 30], 100))
```
* * *
* * *
- 初級 Python
- python 入門
- 安裝 Python3
- 運行 python 程序
- 數據類型和變量
- Python 數字
- Python 字符串
- Python 列表
- Python 字典
- Python 元組
- 數據類型轉換
- Python 控制語句
- Python 函數
- Python 循環
- Python 數學函數
- Python 生成隨機數
- Python 文件處理
- Python 對象和類
- Python 運算符重載
- Python 繼承與多態
- Python 異常處理
- Python 模塊
- 高級 Python
- Python *args和**kwargs
- Python 生成器
- Python 正則表達式
- 使用 PIP 在 python 中安裝包
- Python virtualenv指南
- Python 遞歸函數
- __name__ == "__main__"是什么?
- Python Lambda 函數
- Python 字符串格式化
- Python 內置函數和方法
- Python abs()函數
- Python bin()函數
- Python id()函數
- Python map()函數
- Python zip()函數
- Python filter()函數
- Python reduce()函數
- Python sorted()函數
- Python enumerate()函數
- Python reversed()函數
- Python range()函數
- Python sum()函數
- Python max()函數
- Python min()函數
- Python eval()函數
- Python len()函數
- Python ord()函數
- Python chr()函數
- Python any()函數
- Python all()函數
- Python globals()函數
- Python locals()函數
- 數據庫訪問
- 安裝 Python MySQLdb
- 連接到數據庫
- MySQLdb 獲取結果
- 插入行
- 處理錯誤
- 使用fetchone()和fetchmany()獲取記錄
- 常見做法
- Python:如何讀取和寫入文件
- Python:如何讀取和寫入 CSV 文件
- 用 Python 讀寫 JSON
- 用 Python 轉儲對象