创新互联python教程:
创新互联建站是一家集网站建设,天台企业网站建设,天台品牌网站建设,网站定制,天台网站建设报价,网络营销,网络优化,天台网站推广为一体的创新建站企业,帮助传统企业提升企业形象加强企业竞争力。可充分满足这一群体相比中小企业更为丰富、高端、多元的互联网需求。同时我们时刻保持专业、时尚、前沿,时刻以成就客户成长自我,坚持不断学习、思考、沉淀、净化自己,让我们为更多的企业打造出实用型网站。
编写一个 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
当前名称:Python程序:打印列表中偶数
分享地址:http://www.csdahua.cn/qtweb/news35/305585.html
网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网