zl程序教程

您现在的位置是:首页 >  Python

当前栏目

Python-基础-循环语句快速入门

2023-02-18 16:36:26 时间

控制循环

退出整个循环:

# 退出整个循环
break  

退出当次循环:

# 退出当次循环
continue 

for 循环

# -*- coding: UTF-8 -*-

# 定义一个只有单个字符的列表
source = ['A','B','C','D','E','嗨','害','嗨']

# for语句 遍历列表
# 方法一
for n in source:
    print(n)
print("------------------分割-------------------")

# 方法二,如果下标是0开始,可以省略range中的0
for i in range(0, len(source)):
    print(i,end='\t')
    print(source[i])

print("-----------------分割----------------------")

# 方法三 循环的else用法(while循环也是一样的)
for n in source:
    print(n)
else:
    print("---------------循环结束-------------------")

结果:

A
B
C
D
E
嗨
害
嗨
------------------分割-------------------
0	A
1	B
2	C
3	D
4	E
5	嗨
6	害
7	嗨
-----------------分割----------------------
A
B
C
D
E
嗨
害
嗨
---------------循环结束-------------------

while 循环

# while 循环
count = 0

while count <= 100:
    print("执行了:",count,"次")
    count += 1

print("--------end-------------")

结果:

....
执行了: 97 次
执行了: 98 次
执行了: 99 次
执行了: 100 次
--------end-------------