"""蓝色天空网 mbsky.com: independent, fixed syntax fixtures; never execute source-page scripts."""
import ast,contextlib,copy,io,json,keyword,math,platform,tokenize,unicodedata
CHECKS=[];CASES=[]
def eq(name,actual,expected):
if actual!=expected: raise AssertionError((name,actual,expected))
CHECKS.append(dict(name=name,actual=copy.deepcopy(actual),expected=copy.deepcopy(expected)))
def case(name,source,expected=None,error=None):
namespace={};stream=io.StringIO()
try:
with contextlib.redirect_stdout(stream):exec(compile(source,'<mbsky-owned-'+name+'>','exec'),namespace)
except Exception as exc:
if error is None or not isinstance(exc,error):raise
eq(name+' diagnostic',type(exc).__name__,error.__name__)
CASES.append(dict(name=name,code=source,actual_error=type(exc).__name__,message=str(exc),preserve_format_fields=['code']))
else:
if error is not None:raise AssertionError(name+' did not reject invalid input')
eq(name+' actual output',stream.getvalue(),expected or '')
CASES.append(dict(name=name,code=source,stdout=stream.getvalue(),preserve_format_fields=['code']))
def main():
for name,allowed in [('name_2',True),('_count',True),('姓名',True),('π',True),('2name',False),('user-name',False),('class',False),('x;print(123)',False)]:
eq('safe identifier '+name,name.isidentifier() and not keyword.iskeyword(name),allowed)
eq('soft keyword context',keyword.issoftkeyword('match'),True)
case('unicode normalization','K = 8\nprint(K)\n','8\n')
case('case sensitive','count = 3\nCount = 9\nprint(count, Count)\n','3 9\n')
encoded=b'# coding: cp1252\ntext = "caf\xe9"\n';ns={};exec(compile(encoded,'<mbsky-owned-cp1252>','exec'),ns);eq('actual cp1252 bytes',ns['text'],'café')
try:'中文'.encode('cp1252')
except UnicodeEncodeError:eq('cp1252 cannot encode Chinese',True,True)
else:raise AssertionError('encoding unexpectedly accepted Chinese')
eq('UTF8 source default',compile('姓名="蓝色天空网"'.encode('utf8'),'<mbsky-owned-utf8>','exec')is not None,True)
case('hash comment','print("# is text") # ignored\n','# is text\n')
module=ast.parse('"module documentation"\nanswer=7\n');eq('docstring recognized',ast.get_docstring(module),'module documentation')
plain=ast.parse('answer=7\n"ordinary string expression"\n');eq('later string not docstring',ast.get_docstring(plain),None)
case('valid if suite','if 2 < 3:\n print("learning")\nelse:\n print("later")\n','learning\n')
case('unmatched indentation','if True:\n number=3\n print(number)\n',error=IndentationError)
case('mixed tabs and spaces','if True:\n\tprint(1)\n print(2)\n',error=TabError)
case('explicit joining',r'''value = 2 + \
3 + \
5
print(value)
''','10\n')
case('implicit joining',r'''value = (
2 + # explanation can follow here
3 +
5
)
print(value)
''','10\n')
case('backslash trailing comment','value = 2 + \\ # invalid\n 3\n',error=SyntaxError)
case('blank lines inside string','text = """first\n\nthird"""\nprint(repr(text))\n',"'first\\n\\nthird'\n")
eq('number categories',[type(v).__name__ for v in [10,True,0.25,2+3j]],['int','bool','float','complex'])
eq('bool subtype',issubclass(bool,int),True);eq('complex parts',[(2+3j).real,(2+3j).imag],[2.0,3.0]);eq('float decimal caveat',0.1+0.2==0.3,False)
text='123456789';eq('positive slice',text[2:5],'345');eq('negative stop',text[0:-1],'12345678');eq('first/last characters',[text[0],text[-1]],['1','9']);eq('suffix',text[2:],'3456789');eq('step',text[1:5:2],'24');eq('reverse',text[::-1],'987654321');eq('clamped slice',text[100:],'')
case('slice zero step','print("123"[::0])\n',error=ValueError);case('immutable string','text="sky"\ntext[0]="S"\n',error=TypeError);case('index bounds','print("sky"[9])\n',error=IndexError)
eq('escape compared with raw',[len('\n'),len(r'\n'),repr('\n'),repr(r'\n')],[1,2,"'\\n'","'\\\\n'"])
case('raw cannot end odd slash','text = r"path\\"',error=SyntaxError)
eq('literal concatenation','blue' 'sky','bluesky');eq('repeat','sky'*2,'skysky');eq('no char type',type('sky'[0]).__name__,'str')
case('print end and sep','print("HTML", "CSS", sep=" / ", end=" | ")\nprint("JavaScript")\n','HTML / CSS | JavaScript\n')
out=io.StringIO();returned=out.write('蓝色天空\n');eq('write actual characters',returned,5);eq('written text',out.getvalue(),'蓝色天空\n');eq('UTF8 bytes differ',len(out.getvalue().encode('utf8')),13)
case('simple semicolon statements','first=2; second=3; print(first+second)\n','5\n')
from math import sqrt,isfinite
eq('module vs selected imports',[math.sqrt(81),sqrt(81),isfinite(81)],[9.0,9.0,True])
# Ten independently worded question families correspond to the source teaching goals.
quiz=[
dict(goal='identifier',question='哪个名字可直接作为普通变量名?',options=['3sky','sky-level','_sky_level','sky level'],answer=2,actual='_sky_level'.isidentifier()and not keyword.iskeyword('_sky_level')),
dict(goal='fixed-output',question='print("蓝色天空网") 输出哪一项?',options=['蓝色天空网','None','SyntaxError','空白'],answer=0,actual='蓝色天空网'),
dict(goal='addition',question='print(7 + 8) 的结果?',options=['78','15','7','8'],answer=1,actual=7+8),
dict(goal='range',question='list(range(2, 5)) 的结果?',options=['[2, 3, 4]','[2, 3, 4, 5]','[1, 2, 3]','[5]'],answer=0,actual=list(range(2,5))),
dict(goal='condition',question='当 total=6,if total>4 的分支会执行吗?',options=['不会','会','只在Python2','语法错误'],answer=1,actual=6>4),
dict(goal='function',question='函数返回 a*b,输入2和4得到?',options=['6','24','8','None'],answer=2,actual=(lambda a,b:a*b)(2,4)),
dict(goal='keyword',question='哪个是当前解释器的保留关键字?',options=['define','function','class','variable'],answer=2,actual=keyword.iskeyword('class')),
dict(goal='type',question='type(21).__name__ 的值?',options=['float','bool','str','int'],answer=3,actual=type(21).__name__),
dict(goal='comment',question='字符串外,哪个符号开始单行注释?',options=['//','#','/*','--'],answer=1,actual=next(t.string for t in tokenize.generate_tokens(io.StringIO('# note\n').readline)if t.type==tokenize.COMMENT)),
dict(goal='power',question='3 ** 3 等于?',options=['6','9','27','33'],answer=2,actual=3**3)]
expected=[True,'蓝色天空网',15,[2,3,4],True,8,True,'int','# note',27]
for q,want in zip(quiz,expected):eq('quiz actual '+q['goal'],q['actual'],want)
print(json.dumps(dict(brand='蓝色天空网',domain='mbsky.com',python=platform.python_version(),checks=CHECKS,cases=CASES,quiz=quiz,source_code_executed=False,source_semantic_review='pending',browser_quiz='pending'),ensure_ascii=False))
if __name__=='__main__':main()
本例需在 本地 Python 环境 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地 Python 环境
入口文件:projects/python-lab/python3-basic-syntax.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
python3-basic-syntax.py,或下载右侧课程工程包。 - 确认本地已准备 本地 Python 环境。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip