0
点赞
收藏
分享

微信扫一扫

10. Python的for循环

《Python编程的术与道:Python语言入门》视频课程链接:https://edu.csdn.net/course/detail/27845

For 循环

for循环用于遍历序列(列表、元组、字典、集合或字符串)。

这不太像其他编程语言中的for关键字,而更像其他面向对象编程语言中的迭代器方法那样工作。

使用for循环,我们可以执行一组语句,对列表、元组、集合等中的每个item执行一次。
在这里插入图片描述

# Example: Iterate through a list
colors = ['red', 'green', 'blue', 'yellow']
for x in colors:
    print(x)

red
green
blue
yellow
# Example: Iterate through a string
S = 'python'
for x in S:
    print(x)
p
y
t
h
o
n

break语句

使用break语句,我们可以在循环遍历所有item之前停止循环:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x) 
  if x == "banana":
    break
apple
banana

continue语句

使用continue语句,我们可以停止循环的当前迭代,然后继续下一个:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    continue
  print(x)
apple
cherry

range()函数

要遍历一组代码指定的次数,我们可以使用range()函数,
range()函数返回一个数字序列,默认情况下从0开始,默认情况下以1递增,并以指定的数字结束。

for x in range(6):
  print(x)
0
1
2
3
4
5

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.

for x in range(2, 6):
  print(x)
2
3
4
5
for x in range(2, 30, 3):
  print(x)
2
5
8
11
14
17
20
23
26
29

Else in For Loop

for循环中的else关键字指定循环结束时要执行的代码块:

for x in range(6):
  print(x)
else:
  print("Finally finished!")
0
1
2
3
4
5
Finally finished!
for x in range(6):
    print(x)
    if x == 3:
        break
else:
  print("Finally finished!")
0
1
2
3

注意:for循环中间break的话,else语句不执行

Nested Loops (嵌套循环)

嵌套循环是循环内部的循环。

对于“外循环”的每次迭代,“内循环”将执行一次:

adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
  for y in fruits:
    print(x, y)
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry

pass语句

for循环不能为空,但是如果由于某种原因有一个不带内容的for循环,请放入pass语句,以避免出错。

for x in [0, 1, 2]:
  pass
举报

相关推荐

10.循环(while循环和for循环)

10. 网络

10.指针

10. 信号

10.动态规划

10. v-for

10. 订单管理

10.多线程

0 条评论