編寫一個 Python 程序,使用 For 循環、While 循環和函數打印列表中的偶數,並給出一個實例。
在這個 python 程序中,我們使用 For 循環來迭代這個列表中的每個元素。在 Python 循環中,我們使用 If 語句來檢查偶數。
# Python Program to Print Even Numbers 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)
print("\nEven Numbers in this List are : ")
for j in range(Number):
if(NumList[j] % 2 == 0):
print(NumList[j], end = ' ')
在本 python 程序中,用戶輸入了列表元素= [22,56,7,87]
對於循環–第一次迭代:對於範圍(0,4)
中的 0,循環的條件為真。於是, Python 進入 If 語句
if(NumList[0]% 2 = = 0)= > if(22% 2 = = 0)–條件真
該數字已打印。
第二次迭代:對於範圍(0,4)中的 1–條件為真
如果(NumList[1] % 2 == 0) = >如果(56% 2 = = 0)–條件為真
該數字被打印。
第三次迭代:對於範圍(0,4)中的 2–條件為真
如果(NumList[2] % 2 == 0) = >如果(7% 2 = = 0)–條件為假
這個數字被跳過。
第四次迭代:對於範圍(0,4)中的 3–條件為真
如果(NumList[3] % 2 == 0) = >如果(87% 2 = = 0)–條件為假
跳過此數字。
第五次迭代:對於範圍(0,4)中的 4–條件為假
因此,它從 for 循環中退出
列表程序中的這個 Python 偶數和上面的一樣。我們剛剛將 For 循環替換為 While 循環。
NumList = []
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)
print("\nEven Numbers in this List are : ")
while(j < Number):
if(NumList[j] % 2 == 0):
print(NumList[j], end = ' ')
j = j + 1
Please enter the Total Number of List Elements: 5
Please enter the Value of 1 Element : 12
Please enter the Value of 2 Element : 13
Please enter the Value of 3 Element : 55
Please enter the Value of 4 Element : 66
Please enter the Value of 5 Element : 90
Even Numbers in this List are :
12 66 90
清單程序中的 Python 偶數與第一個示例相同。然而,我們使用功能分離邏輯。
def even_numbers(NumList):
for j in range(Number):
if(NumList[j] % 2 == 0):
print(NumList[j], end = ' ')
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)
print("\nEven Numbers in this List are : ")
even_numbers(NumList)
Please enter the Total Number of List Elements: 6
Please enter the Value of 1 Element : 22
Please enter the Value of 2 Element : 33
Please enter the Value of 3 Element : 44
Please enter the Value of 4 Element : 55
Please enter the Value of 5 Element : 66
Please enter the Value of 6 Element : 88
Even Numbers in this List are :
22 44 66 88
原創文章,作者:EQ64K,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/126689.html