教程 / Python / 数据科学 / Python2.x
continue 跳过本轮而保留后续轮次
核对字符串过滤、while 计数更新和正常耗尽。
本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。
学完这一章,你能够
- 核对字符串过滤、while 计数更新和正常耗尽。
把控制流送到下一轮
continue 跳过当前循环体余下的语句。for 从迭代器读取下一项,while 返回条件检查。嵌套中的 continue 作用于最近的循环。
同一循环最终正常耗尽时,continue 不阻止 else。如果 continue 穿过带 finally 的 try,仍会先运行清理。
先推进状态,再决定是否记录
遍历文本时只跳过选定的字符,后续仍然输出。while 里先递减,再检查当前值是否需要跳过,这样跳过本轮也不会停在同一个值上。
本站从 7 递减到 0,跳过 3 但仍包括 0。这里判断检查与日志顺序是输出包含 0 的原因。
运行跳过值与正常耗尽
python · 阅读源码
import json
def without(text, skip):
result = []
for char in text:
if char == skip:
continue
result.append(char)
else:
result.append("exhausted")
return result
def descending(start, skip):
result = []
while start > 0:
start -= 1
if start == skip:
continue
result.append(start)
else:
result.append("exhausted")
return result
print(json.dumps({"continue_for_and_while": [
without("north", "r"), without("rr", "r"),
descending(7, 3), descending(0, 3),
]}))
events = []
for value in (1, 2):
try:
if value == 1:
continue
events.append(["recorded", value])
finally:
events.append(["cleanup", value])
else:
events.append(["else"])
print(json.dumps({"continue_runs_finally": events}))
预期结果 · 待实际运行核验
- north 跳过 r 后得到 n、o、t、h。递减序列为 6、5、4、2、1、0,循环最终正常耗尽。
运行跳过值与正常耗尽
所需环境:Python 3.12
当前源码 SHA256:b90df43fb027018b584591453b096f962f94ecc59250ceeae7ae5965077cd13b
常见错误与边界
- 核对目标解释器版本、环境条件和输入后,再比较实际输出。
练习与解答
若在 while 循环顶部先检查 0,再递减并输出,最后一次输出会落在哪个值?
展开参考解答
从 1 进入本轮,递减后仍会记录 0。若改成递减后先判断 0 并跳过,0 才会被省略。