• 遍历循环
• 无限循环
• 循环控制保留字
• 循环的高级用法

# 二、遍历循环

``````for <循环变量> in <遍历结构>:
<语句块>
``````
• 从遍历结构中逐一提取元素，放在循环变量中
• 由保留字`for``in`组成，完整遍历所有元素后结束
• 每次循环，所获得元素放入循环变量，并执行

# 三、遍历循环的应用

## 3.1 计数循环(N次)

``````fro i in range(N):
<语句块>
``````
• 遍历由`range()`函数产生的数字序列，产生循环
``````for i in range(5):
print(i)
``````
``````0
1
2
3
4
``````
``````for i in range(5):
print(‘hello:‘, i)
``````
``````hello: 0
hello: 1
hello: 2
hello: 3
hello: 4
``````

## 3.2 计数循环(特定次)

``````fro i in range(M,N,K):
<语句块>
``````
• 遍历由`range()`函数产生的数字序列，产生循环
``````for i in range(1, 6):
print(i)
``````
``````1
2
3
4
5
``````
``````for i in range(1, 6, 2):
print(‘hello:‘, i)
``````
``````hello: 1
hello: 3
hello: 5
``````

## 3.3 字符串遍历循环

``````for c  in  s:
<语句块>
``````
• s是字符串，遍历字符串每个字符，产生循环
``````for c in ‘python‘:
print(c, end=‘,‘)
``````
``````p,y,t,h,o,n,
``````

## 3.4 列表遍历循环

``````for item  in  ls:
<语句块>
``````
• ls是一个列表，遍历其每个元素，产生循环
``````for item in [123, "PY", 456]:
print(item, end=",")
``````
``````123,PY,456,
``````

## 3.5 文件遍历循环

``````for line in  fi:
<语句块>
``````
• fi是一个文件标识符，遍历其每行，产生循环
``````# fi.txt

``````
``````for line in fi:
print(line)
``````
``````优美胜于丑陋

``````

# 四、无限循环

• 反复执行语句块，直到条件不满足时结束
``````a = 3
while a > 0:
a = a - 1
print(a)
``````
``````2
1
0
``````
``````# 死循环， (CTRL + C 退出执行)
a = 3
while a > 0:
a = a + 1
print(a)
``````

# 五、循环控制保留字

## 5.1 break 和 continue

• break跳出并结束当前整个循环，执行循环后的语句
• continue结束当次循环，继续执行后续次数循环
• break和continue可以与for和while循环搭配使用

### 5.1.1 for

``````for c in "PYTHON":
if c == ‘T‘:
continue
print(c, end=‘,‘)
``````
``````P,Y,H,O,N,
``````
``````for c in "PYTHON":
if c == ‘T‘:
break
print(c, end=‘,‘)
``````
``````P,Y,
``````

### 5.1.2 while

• break仅跳出当前最内层循环
``````s = "PYTHON"
while s != "":
for c in s:
print(c, end=‘,‘)
s = s[:-1]
``````
``````P,Y,T,H,O,N,P,Y,T,H,O,P,Y,T,H,P,Y,T,P,Y,P,
``````
``````s = "PYTHON"
while s != "":
for c in s:
if c == ‘T‘:
break
print(c, end=‘,‘)
s = s[:-1]
``````
``````P,Y,P,Y,P,Y,P,Y,P,Y,P,
``````

# 六、循环的高级用法

## 6.1 循环的扩展

### 6.1.1 for

``````for <变量> in <遍历结构>:
<语句块1>
else:
<语句块2>
``````

### 6.1.2 while

``````while <条件>:
<语句块1>
else:
<语句块2>
``````
• 当循环没有被break语句退出时，执行else语句块
• else语句块作为"正常"完成循环的奖励
• 这里else的用法与异常处理中else用法相似
``````for c in "PYTHON":
if c == "T":
continue
print(c, end="")
else:
print("正常退出")
``````
``````PYHON正常退出
``````
``````for c in "PYTHON":
if c == "T":
break
print(c, end="")
else:
print("正常退出")
``````
``````PY
``````

# 七、单元小结

• `for…in` 遍历循环：计数、字符串、列表、文件…
• `while`无限循环
• `continue``break`保留字：退出当前循环层次
• 循环else的高级用法：与`break`有关

025 程序的循环结构

(0)
(0)