流程控制之for循环

流程控制之for循环

一、语法

有了骚气的while循环,为什么还满足不了那个需求呢,为什么还需要for ,看看下面的问题,给出一个列表,要取出列表里面的所有数据取出来,该怎么做呢,下面看看while如何实现:

eg(while):

nums_list = [1, 2, 3, 4]

n = 0
while n < 4:
    # while n < len(name_list):
    print(nums_list[n])
    n += 1

结果:
1
2
3
4

在字典也有去多个值的需求,字典可能有while循环无法使用了,这个时候可以使用我们的for循环,骚操作一下,让他彻底的满足。

eg:

info = {'name': 'randy', 'age': 18}

for item in info:
    # 取出info的keys
    print(item)

结果:
randy
18

再看看列表:
eg:

nums_list = [1, 2, 3, 4]
for item in nums_list:
    print(item)

结果:
1
2
3
4

看出for循环,骚里骚气的操作了吗,for循环的次数受限于容器类型的长度,而while循环的循环次数需要自己控制。for循环也可以按照索引取值,在看看下面一波骚操作。

for i in range(1, 10):  # range顾头不顾尾
    print(i)

1
2
3
4
5
6
7
8
9

二、for+break

for循环和while循环一样,都可以使用break跳出

出本层循环。

# for+break
nums_list = [1, 2, 3, 4]
for nums in nums_list:
    if nums == 2:
        break
    print(nums)

结果:

1

三、 for+continue

for循环调出本次循环,进入下一次循环

# for+continue
nums_list = [1, 2, 3, 4]
for nums in nums_list:
    if nums == 2:
        continue
    print(nums)

四、for循环嵌套

外层循环循环一次,内层循环循环所有的。

eg:

# for循环嵌套
for i in range(3):
    print(f'-----:{i}')
    for j in range(2):
        print(f'*****:{j}')

结果:

-----:0
**:0
**
:1
-----:1
**:0
**
:1
-----:2
**:0
**
:1

五、for+else

for循环没有break的时候触发else内部代码块和while+else一样。

eg:

# for+else
nums_list = [1, 2, 3, 4]
for nums in nums_list:
    print(nums)
else:
    print('for循环没有被break中断掉')

结果:
1
2
3
4
for循环没有被break中断掉

六、for循环实现loading

eg(最好在cmd窗口中运行或采用交互的方法):

import time

print('Loading', end='')
for i in range(6):
    print(".", end='')
    time.sleep(0.2)

结果:Loading......

在当下的阶段,必将由程序员来主导,甚至比以往更甚。
原文地址:https://www.cnblogs.com/randysun/p/11284686.html