for
循环和while
循环在常用过程中经常会被忘记具体的使用方法,如下进行了模块化总结,同时请大家记住一句话:for......else
和while......else
正常奖励else
,深入理解如下
for <变量> in <遍历结构>:
<语句块1>
else:
<语句块2>
while <条件>:
<语句块1>
else:
<语句块2>
for
遍历结构含有计数循环(N次)、字符串遍历循环、列表便利循环、文件便利循环…
- 当循环没有被
break
语句退出时,执行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
和while
循环中使用else
语句,else
的正常运行取决于for循环是否执行break
语句,若整个过程均无,则奖励else
语句运行。
注意,continue
语句不影响else
语句的执行哦