目標(biāo):定義一個數(shù)字列表,并計算列表元素之和。
例如: 輸入 : [12, 15, 3, 10] 輸出 : 40
方法一:
total = 0 list1 = [11, 5, 17, 18, 23] for ele in range(0, len(list1)): total = total + list1[ele] print("列表元素之和為: ", total)
結(jié)果:
列表元素之和為: 74
方法二:使用while()循環(huán)
total = 0 ele = 0 list1 = [11, 5, 17, 18, 23] while(ele < len(list1)): total = total + list1[ele] ele += 1 print("列表元素之和為: ", total)
以上實例輸出結(jié)果為:
列表元素之和為: 74
方法三:使用遞歸
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)
結(jié)果:
列表元素之和為: 74
推薦教程:python教程