Python 程序:在列表中打印偶数

编写一个 Python 程序,使用 For 循环、While 循环和函数以及实际示例来打印列表中的偶数。您可以使用循环迭代列表项,并使用 If 语句检查列表项是否能被 2 整除。如果为 True,则表示偶数,打印它。

Python 程序:使用 For 循环在列表中打印偶数

在此 Python 程序中,我们使用 For 循环迭代此列表中的每个元素。我们在循环中使用 If 语句来检查偶数。

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 Program to Print Even Numbers in a List using for loop

在此 Python 程序中,用户输入的 列表元素为 = [22, 56, 7, 87]

For 循环 - 第一次迭代:for 0 in range(0, 4)。For 循环条件为 True。因此,Python 进入 If 语句。

if(NumList[0] % 2 == 0) => if(22 % 2 == 0) – 条件为 True。此数字将被打印。

第二次迭代:for 1 in range(0, 4) – 条件为True
if(NumList[1] % 2 == 0) => if(56 % 2 == 0) – 条件为 True。因此,此数字将被打印。

第三次迭代:for 2 in range(0, 4) – 条件为True
if(NumList[2] % 2 == 0) => if(7 % 2 == 0) – 条件为 False。因此,此数字被跳过。

第四次迭代:for 3 in range(0, 4) – 条件为True
if(NumList[3] % 2 == 0) => if(87 % 2 == 0) – 条件为 False。因此,此数字被跳过。

第五次迭代:for 4 in range(0, 4) – 条件为 False。因此,它退出 For 循环

Python 程序:使用 While 循环在列表中打印偶数

此示例与上面相同。我们只是将 For 循环替换为 While 循环,并且请不要忘记增加 j 的值(j = j + 1)。

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 1 Element : 13
Please enter the Value of 1 Element : 55
Please enter the Value of 1 Element : 66
Please enter the Value of 1 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)
Python Program to Print Even Numbers in a List using functions