蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行本章核心实例

PYTHON本地 Python 环境python3-loop.py
python3-loop.py209 行
"""蓝色天空网 mbsky.com — 循环、else和真实有界观察。"""
import sys,io,contextlib,subprocess,time,keyword
from pathlib import Path
sys.path.insert(0,str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks

def forever_child():
    n=0
    while True:
        print(n,flush=True);n+=1;time.sleep(0.02)

def main():
    if len(sys.argv)>1 and sys.argv[1]=="--bounded-observe-infinite":
        forever_child();return
    c=Checks();total=0;counter=1
    while counter<=100:total+=counter;counter+=1
    c.eq("while sum 1 through100",total,5050)
    c.eq("while final state",counter,101)
    numbers=[];count=0
    while count<5:numbers.append(count);count+=1
    else:numbers.append(("else",count))
    c.eq("while natural else",numbers,[0,1,2,3,4,("else",5)])
    trace=[]
    while False:trace.append("body")
    else:trace.append("else")
    c.eq("while zero iterations else",trace,["else"])
    odds=[];n=1
    while n<10:odds.append(n);n+=2
    c.eq("loop GIF odd sequence",odds,[1,3,5,7,9])
    c.eq("loop GIF final n",n,11)
    c.eq("for themes",[value for value in["HTML","CSS","JavaScript"]],["HTML","CSS","JavaScript"])
    chars=[]
    for ch in"mbsky":chars.append(ch)
    c.eq("for text characters",chars,["m","b","s","k","y"])
    c.eq("for 1 through5",list(range(1,6)),[1,2,3,4,5])
    trace=[]
    for n in range(6):trace.append(n)
    else:trace.append("else")
    c.eq("for exhausted else",trace,[0,1,2,3,4,5,"else"])
    trace=[]
    for n in[]:trace.append(n)
    else:trace.append("else")
    c.eq("for empty still else",trace,["else"])
    trace=[]
    for name in["HTML","CSS","JavaScript"]:
        if name=="CSS":trace.append("break");break
        trace.append(name)
    else:trace.append("else")
    trace.append("after")
    c.eq("for break skips else",trace,["HTML","break","after"])
    trace=[]
    for n in range(3):
        if n==1:continue
        trace.append(n)
    else:trace.append("else")
    c.eq("continue permits else",trace,[0,2,"else"])
    trace=[];n=0
    while n<3:
        n+=1
        if n==2:break
        trace.append(n)
    else:trace.append("else")
    c.eq("while break suppresses else",trace,[1])
    trace=[];n=0
    while n<3:
        n+=1
        if n==2:continue
        trace.append(n)
    else:trace.append("else")
    c.eq("while continue permits else",trace,[1,3,"else"])
    def returns():
        for n in range(1):return "returned"
        else:return "else"
    c.eq("return not loop else",returns(),"returned")
    trace=[]
    def failing():
        for n in range(1):raise ValueError("owned loop error")
        else:trace.append("else")
    c.raises("exception not loop else",ValueError,failing)
    c.eq("exception did not append else",trace,[])
    trace=[]
    for outer in range(2):
        for inner in range(2):trace.append((outer,inner));break
        else:trace.append("inner-else")
    else:trace.append("outer-else")
    c.eq("break only nearest loop",trace,[(0,0),(1,0),"outer-else"])
    for name,r,expected in [
        ("stop",range(5),[0,1,2,3,4]),
        ("start stop",range(5,9),[5,6,7,8]),
        ("positive step",range(0,10,3),[0,3,6,9]),
        ("negative step",range(-10,-100,-30),[-10,-40,-70]),
        ("wrong direction",range(1,5,-1),[])]:
        c.eq("range "+name,list(r),expected)
    c.eq("range type",type(range(3)).__name__,"range")
    c.eq("range not its iterator",iter(range(3))is range(3),False)
    c.eq("range reusable",list(range(3))==list(range(3)),True)
    c.raises("range zero step",ValueError,lambda:range(0,2,0))
    c.raises("range float fails",TypeError,lambda:range(1.5))
    class Indexed:
        def __index__(self):return 3
    c.eq("range index protocol",list(range(Indexed())),[0,1,2])
    topics=["HTML","CSS","JS"]
    c.eq("index with range len",[(i,topics[i])for i in range(len(topics))],[(0,"HTML"),(1,"CSS"),(2,"JS")])
    c.eq("enumerate default",list(enumerate(topics)),[(0,"HTML"),(1,"CSS"),(2,"JS")])
    c.eq("enumerate custom start",list(enumerate(topics,1)),[(1,"HTML"),(2,"CSS"),(3,"JS")])
    c.raises("enumerate start integer",TypeError,lambda:enumerate(topics,0.5))
    it=iter([1,2]);c.eq("iterator first pass",list(it),[1,2]);c.eq("iterator second exhausted",list(it),[])
    def countdown(skip=False):
        result=[];n=5
        while n>0:
            n-=1
            if n==2:
                if skip:continue
                break
            result.append(n)
        return result
    c.eq("while break countdown",countdown(),[4,3])
    c.eq("while continue countdown",countdown(True),[4,3,1,0])
    n=10;out=[]
    while n>0:
        out.append(n);n-=1
        if n==5:break
    c.eq("decrement then break",out,[10,9,8,7,6])
    n=10;out=[]
    while n>0:
        n-=1
        if n==5:continue
        out.append(n)
    c.eq("decrement then continue",out,[9,8,7,6,4,3,2,1,0])
    letters=[]
    for char in"mbsky":
        if char=="y":break
        letters.append(char)
    c.eq("for break characters","".join(letters),"mbsk")
    filtered=[]
    for char in"mbook":
        if char=="o":continue
        filtered.append(char)
    c.eq("for continue characters",filtered,["m","b","k"])
    trace=[]
    for n in range(2):
        try:
            if n==0:continue
            break
        finally:trace.append(("cleanup",n))
    else:trace.append("else")
    c.eq("finally runs before continue break",trace,[("cleanup",0),("cleanup",1)])
    prime_records=[]
    for n in range(2,10):
        for x in range(2,n):
            if n%x==0:prime_records.append((n,x,n//x));break
        else:prime_records.append((n,"prime"))
    c.eq("prime and first factors",prime_records,[(2,"prime"),(3,"prime"),(4,2,2),(5,"prime"),(6,2,3),(7,"prime"),(8,2,4),(9,3,3)])
    trace=[]
    for char in"moom":
        if char=="o":pass;trace.append("pass reached")
        trace.append(char)
    c.eq("pass never skips remaining body",trace,["m","pass reached","o","pass reached","o","m"])
    class Empty:
        pass
    c.eq("minimum class",isinstance(Empty(),Empty),True)
    c.raises("comment cannot supply suite",IndentationError,lambda:compile("if True:\n # comment only\n","<owned-comment>","exec"))
    c.eq("pass reserved keyword",keyword.iskeyword("pass"),True)
    out=io.StringIO()
    with contextlib.redirect_stdout(out):
        exec(compile('if None:\n    print("unused")','<owned-corrected-quiz>','exec'),{})
    c.eq("None false with valid quotes",out.getvalue(),"")
    c.raises("curly quotes are syntax error",SyntaxError,lambda:compile('if None:\n    print(“unused”)','<owned-curly>','exec'))
    c.eq("quiz each plus one",[i+1 for i in[1,0]],[2,1])
    i=total=0
    while i<=4:total+=i;i+=1
    c.eq("quiz sum0 through4",total,10)
    out=io.StringIO()
    with contextlib.redirect_stdout(out):
        for char in"PYTHON STRING":
            if char==" ":break
            print(char,end="")
            if char=="O":continue
    c.eq("continue after output does not erase O",out.getvalue(),"PYTHON")
    # 图示两级过滤的顺序:被continue跳过的名字到不了后面的break。
    def diagram(length):
        log=[]
        for name in["Python","HTML","Flask","JavaScript","CSS"]:
            if len(name)!=length:continue
            log.append(name)
            if name=="JavaScript":break
        log.append("Done")
        return log
    c.eq("figure break unreachable after filtering",diagram(4),["HTML","Done"])
    c.eq("figure adjusted length reaches break",diagram(10),["JavaScript","Done"])
    proc=subprocess.Popen([sys.executable,"-I","-B","-X","utf8",__file__,"--bounded-observe-infinite"],stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,encoding="utf8")
    try:prefix=[proc.stdout.readline().strip()for _ in range(3)];c.eq("true loop real output prefix",prefix,["0","1","2"])
    finally:
        proc.terminate();stdout,stderr=proc.communicate(timeout=5)
    c.eq("owned infinite observer cleaned",proc.poll()is not None,True)
    quiz=[
     dict(question="弯引号已改为普通引号:if None中的输出会运行吗?",options=["不会输出","会输出一次","会死循环"],answer=0),
     dict(question="普通if/elif/else链选择首个真分支后会怎样?",options=["继续判断其它elif","不再判断后面的elif","还必须执行else"],answer=1),
     dict(question="遍历[1,0]并逐项加1,依次得到?",options=["2和1","列表[2,1]作为单次print","只有2"],answer=0),
     dict(question="哪些循环支持else子句?",options=["仅for","仅while","for与while"],answer=2),
     dict(question="从0累加到4(包含4)得到?",options=["4","10","15"],answer=1),
     dict(question="while True每轮输出,且无退出操作时?",options=["固定4轮","持续运行直至被中断或异常","不会运行"],answer=1),
     dict(question="普通逐项遍历通常更直接的写法?",options=["for;while也可以实现","while无法遍历","for保证所有场景更快"],answer=0),
     dict(question="哪一组控制作用准确?",options=["pass退出、break空操作","break退最近循环,continue下一轮","continue退出所有循环"],answer=1),
     dict(question="输出PYTHON各字符后遇O才continue,遇空格break,结果?",options=["PYTHN","PYTHON","STRING"],answer=1),
     dict(question="pass的作用?",options=["跳过本轮后面语句","终止循环","合法空语句占位"],answer=2)]
    c.finish("python3-loop",quiz=quiz,infinite_process=dict(observed_prefix=prefix,termination="parent terminated owned process; not keyboard Ctrl+C"),original_GIF_goal=odds)
if __name__=="__main__":main()
本例需在 本地 Python 环境 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地 Python 环境

入口文件:projects/python-lab/python3-loop.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 python3-loop.py,或下载右侧课程工程包。
  2. 确认本地已准备 本地 Python 环境。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习