Python 計算列表元素之和

Document 對象參考手冊 Python3 實例

定義一個數字列表,並計算列表元素之和。

例如: 輸入 : [12, 15, 3, 10] 輸出 : 40

實例 1

total = 0
 
list1 = [11, 5, 17, 18, 23]  
 
for ele in range(0, len(list1)):
    total = total + list1[ele]
 
print("列表元素之和為: ", total)

以上實例輸出結果為:

列表元素之和為:  74

實例 2: 使用 while() 迴圈

total = 0
ele = 0
 
list1 = [11, 5, 17, 18, 23]  
 
while(ele < len(list1)):
    total = total + list1[ele]
    ele += 1
     
print("列表元素之和為: ", total)

以上實例輸出結果為:

列表元素之和為:  74

實例 3: 使用遞歸

list1 = [11, 5, 17, 18, 23]

def sumOfList(list, size):
   if (size == 0):
     return 0
   else:
     return list[size - 1] + sumOfList(list, size - 1)
     
total = sumOfList(list1, len(list1))

print("列表元素之和為: ", total)

以上實例輸出結果為:

列表元素之和為:  74

Document 對象參考手冊 Python3 實例