首页 > 编程语言 > 详细

Python 学习笔记9 循环语句 For in

时间:2019-04-18 21:18:42      阅读:206      评论:0      收藏:0      [点我收藏+]

For in 循环主要适用于遍历一个对象中的所有元素。我们可以使用它遍历列表,元组和字典等等。

其主要的流程如下:(图片来源于: https://www.yiibai.com/python/python_for_loop.html

技术分享图片

 使用For遍历一个列表:

peoples = [Ralf, Clark, Leon, Terry]
for people in peoples:
    print(people)

‘‘‘
输出:
Ralf
Clark
Leon
Terry
‘‘‘

 

使用For in 遍历一个字典:

ralf = {name: Ralf, sex: male, height: 188}

for key, value in ralf.items():
    print(key + ":" + value)

‘‘‘
输出:
name:Ralf
sex:male
height:188
‘‘‘

 

在For 循环中,我们可以使用 break, 在遇到特殊条件时,中断循环操作:

peoples = [Ralf, Clark, Leon, Terry, Mary]
for people in peoples:
    if people == Terry:
        break
    print(people)

‘‘‘
输出:
Ralf
Clark
Leon
‘‘‘

 

使用continue在for中继后继续下一轮的循环。

peoples = [Ralf, Clark, Leon, Terry, Mary]
for people in peoples:
    if people == Terry:
        continue
    print(people)

‘‘‘
输出:
Ralf
Clark
Leon
Mary
‘‘‘

 

For 循环中也可以使用else结构,当循环结束时执行特定语句,但是break中断时,else里面数据不会被执行:

peoples = [Ralf, Clark, Leon, Terry, Mary]
for people in peoples:
    print(people)
else:
    print(Loop is end)
‘‘‘
输出:
Ralf
Clark
Leon
Terry
Mary
Loop is end
‘‘‘


peoples = [Ralf, Clark, Leon, Terry, Mary]
for people in peoples:
    if people == Terry:
        break
    print(people)
else:
    print(Loop is end)

‘‘‘
输出:
Ralf
Clark
Leon
‘‘‘

 

Python 学习笔记9 循环语句 For in

原文:https://www.cnblogs.com/wanghao4023030/p/10732381.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!