跳转至

for 循环

for 循环语法 #card

for iterating_var in sequence:
  statements

^1662296899486

参数 描述
for for 循环使用的关键字
iterating_var for 循环每次迭代使用的变量
in for 循环使用的关键字
sequence for 循环需要遍历的变量
statements 每次循环执行的语句
  1. 所有在 for 循环或者 while 循环中的声明,必须使用相同的缩进值。否则会出现语法错误。
  2. for循环可以嵌套使用。

案例1:循环处理序列元素 #card

mylist = [1, 2, 3, 4]
for i in mylist:
    print(i)

^1662298241117

在第1次循环时,值 1 被传递给 i,第2次循环时,值 2 被传递给 i。循环一直到列表变量 mylist 没有更多元素时停止。运行结果为:

1
2
3
4

案例2: 循环处理字典内容 #card

"""在字典中循环时,用 `items()` 方法可同时取出键和对应的值:"""
books = {'标题': 'Python一学就会', '作者': '小明'}
for k, v in books.items():
    print(k, v)
out:
标题 Python一学就会
作者 小明

^1662298241127

案例3: 循环处理序列的索引和值 #card

"""在序列中循环时,用enumerate()函数可以同时取出位置索引和对应的值:"""
for i, v in enumerate(['tic', 'tac', 'toe']):
    print(i, v)
...
0 tic
1 tac
2 toe

^1662298241135

案例4: 循环处理多个序列 #card

"""同时循环两个或多个序列时,用zip()函数可以将其内的元素一一匹配"""
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
   print('What is your {0}?  It is {1}.'.format(q, a))
"""结果:
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.
"""

^1662298241142

案例5:在一定范围内循环 #card

"""range()函数能够指定循环的起始值和结束值,从而让循环体在指定的范围内循环。例如:"""
for i in range(10):
    print(i)                    # 0-9
for i in range(1,10):
    print(i)                    # 1-9
for i in range(1,10,2):
    print(i)                    # 1,3,5,7

^1662298241151

range() 函数只有 1 个参数时,表示从 0 开始循环;两个参数时,第一个参数是起始值,第二个参数是结束值;三个参数时,第三个参数表示循环步长。

参考文献

  1. 8. Compound statements — Python 3.10.6 documentation

最后更新: 2022年10月15日 01:02:48
创建日期: 2022年9月5日 00:56:03
Contributers: yangjh