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

时间:2023-03-08 20:25:02

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

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

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

使用For遍历一个列表:

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

使用For in 遍历一个字典:

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

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
'''