Python学习笔记10(RUNOOB)

for 语句

Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。

for循环的一般格式如下:

for < variable > in < sequence >:
< statements >
else :
< statements >



# for循环
color = ['red', 'blue', 'green', 'white', 'black', 'gray']
for i in color:
    if i == 'white':
        print("白色找到了!")
        break
    else:
        print(i)
else:
    print("错误循环")

range()函数

# range()函数
# 1.遍历数字序列
print("1.遍历数字序列:")
for i in range(10):
    print(i)

# 2.指定区间的值
print("2.指定区间的值:")
for i in range(5, 10):
    print(i)

# 3.以指定数字开始并指定不同的增量(步长)
print("3.以指定数字开始并指定不同的增量(步长):")
for i in range(2, 30, 4):
    print(i)

# 4.结合range()len()函数以遍历一个序列的索引
print("4.结合range()len()函数以遍历一个序列的索引:")
color = ['red', 'blue', 'green', 'white', 'black', 'gray']
for i in range(len(color)):
    print(i, color[i])

输出结果:

1.遍历数字序列:
0
1
2
3
4
5
6
7
8
9
2.指定区间的值:
5
6
7
8
9
3.以指定数字开始并指定不同的增量(步长):
2
6
10
14
18
22
26
4.结合range()和len()函数以遍历一个序列的索引:
0 red
1 blue
2 green
3 white
4 black

5 gray

break和continue语句

# break()continue()
# break 语句:直接跳出当前 for  while 的循环体。
print("break语句执行结果:")
for i in range(2,10):
    if i == 6:
        break
    print(i)

# continue语句:跳过当前循环块中的剩余语句,然后继续进行下一轮循环。
print("continue语句执行结果:")
for i in range(2,10):
    if i == 6:
        continue
    print(i)

输出结果:

break语句执行结果:
2
3
4
5
continue语句执行结果:
2
3
4
5
7
8
9

猜你喜欢

转载自blog.csdn.net/weixin_42385291/article/details/80810751