寫一個 Python 程序,用一個實際例子找到列表中元素的和。
Python 程序查找列表中元素的和
這個 python 程序允許用戶輸入列表的長度。接下來,我們使用 Python For Loop 向列表中添加數字。
Python sum 函數返回列表中所有元素的 sum 。
# Python Program to find Sum of all Elements in a List
NumList = []
Number = int(input("Please enter the Total Number of List Elements : "))
for i in range(1, Number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
NumList.append(value)
total = sum(NumList)
print("\n The Sum of All Element in this List is : ", total)
不使用求和在列表中查找元素求和的程序
在這個程序中,我們使用 For Loop 來迭代這個列表中的每個元素。在循環中,我們將這些元素添加到總變數中。
NumList = []
total = 0
Number = int(input("Please enter the Total Number of List Elements : "))
for i in range(1, Number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
NumList.append(value)
for j in range(Number):
total = total + NumList[j]
print("\n The Sum of All Element in this List is : ", total)
Python 列表項的總和輸出
Please enter the Total Number of List Elements : 5
Please enter the Value of 1 Element : 10
Please enter the Value of 2 Element : 20
Please enter the Value of 3 Element : 30
Please enter the Value of 4 Element : 40
Please enter the Value of 5 Element : 55
The Sum of All Element in this List is : 155
使用 While 循環計算列表中元素總和的 Python 程序
這個返回列表項總和的 Python 程序與上面的相同。我們剛剛將 For 循環替換為 While 循環。
NumList = []
total = 0
j = 0
Number = int(input("Please enter the Total Number of List Elements : "))
for i in range(1, Number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
NumList.append(value)
while(j < Number):
total = total + NumList[j]
j = j + 1
print("\n The Sum of All Element in this List is : ", total)
使用 while 循環輸出的列表項的總和
Please enter the Total Number of List Elements : 6
Please enter the Value of 1 Element : 10
Please enter the Value of 2 Element : 20
Please enter the Value of 3 Element : -30
Please enter the Value of 4 Element : -40
Please enter the Value of 5 Element : 50
Please enter the Value of 6 Element : 100
The Sum of All Element in this List is : 110
使用函數計算列表中所有元素總和的 Python 程序
這個求列表項總和的程序和第一個例子一樣。但是,我們使用函數分離了 python 程序邏輯。
def sum_of_list(NumList):
total = 0
for j in range(Number):
total = total + NumList[j]
return total
NumList = []
Number = int(input("Please enter the Total Number of List Elements : "))
for i in range(1, Number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
NumList.append(value)
total = sum_of_list(NumList)
print("\n The Sum of All Element in this List is : ", total)
使用函數輸出的列表項的總和
Please enter the Total Number of List Elements : 7
Please enter the Value of 1 Element : 19
Please enter the Value of 2 Element : 11
Please enter the Value of 3 Element : 32
Please enter the Value of 4 Element : 86
Please enter the Value of 5 Element : 567
Please enter the Value of 6 Element : 32
Please enter the Value of 7 Element : 9
The Sum of All Element in this List is : 756
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/302011.html