首页 > 编程知识 正文

Python 程序:打印列表中偶数

时间:2023-11-24 15:33:41 阅读:308909 作者:OUBV

编写一个 Python 程序,使用 For 循环、While 循环和函数打印列表中的偶数,并给出一个实例。

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

在这个 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 循环中退出

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

列表程序中的这个 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 程序

清单程序中的 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 

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。