10. Python的for循环

《Python编程的术与道:Python语言入门》视频课程
《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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bai666ai

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值