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

开始 Python 基础综合测验

PYTHON本地浏览器python-quiz.py
python-quiz.py134 行
"""蓝色天空网 mbsky.com | Compute the answers to the authored beginner quiz."""
import ast
from contextlib import redirect_stdout
import io
import json
from pathlib import Path
import sys
from tempfile import TemporaryDirectory, gettempdir
import tokenize

sys.path.insert(0, str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks


QUESTIONS = [
    ("执行 print('gate', 7, sep='='),输出一行什么?", ["gate 7", "gate=7", "gate7"], 1, "sep 指定各参数之间的分隔符。"),
    ("哪一行可用 Python 给名称 rate 绑定整数?", ["$rate = 4", "var rate = 4", "rate = 4"], 2, "赋值语句左侧可直接写名称。"),
    ("检查 level = '#' # audit,真正的注释部分是哪段?", ["字符串中的 #", "# audit", "两处 # 都开始注释"], 1, "引号内的井号属于字符串。"),
    ("label = '''东门''' 运行后,label 的类型是什么?", ["str", "NoneType", "没有这个名称"], 0, "三引号可界定字符串。"),
    ("count = 6 执行后,count 绑定到什么值?", ["'6'", "6", "未绑定"], 1, "没有引号的 6 是整数常量。"),
    ("int('17') 返回什么?", ["'17'", "17.0", "17"], 2, "int 解析字符串中的整数表示。"),
    ("total 已为整数,哪种运算符不能用来更新它?", ["+=", "~=", "*="], 1, "Python 支持 +=、-=、*= 等,语法中没有 ~=。"),
    ("class Parcel: pass,创建 Parcel() 后,哪个关系成立?", ["type(Parcel()) is Parcel", "type(Parcel()) is dict", "Parcel 不能创建实例"], 0, "类语句可定义用户自己的类型。"),
    ("['东门', 4, False] 是什么容器?", ["set", "tuple", "list"], 2, "列表中可存放不同类型的对象。"),
    ("values = [5, 8, 13],values[:20] 返回什么?", ["[5, 8, 13]", "IndexError", "[8, 13]"], 0, "切片终点超过长度时可截取到末尾。"),
    ("float('7.25') 得到什么?", ["整数 7", "浮点数 7.25", "字符串 '7.25'"], 1, "float 按浮点表示转换文本。"),
    ("哪一个 Python 条件头可与下一行缩进语句组成 if?", ["if mark >= 3:", "if mark => 3:", "if mark >= 3"], 0, "使用 >= 并以冒号结束条件头。"),
    ("要在 if 后继续写一个独立条件分支,应使用什么?", ["elseif", "except", "elif"], 2, "elif 在前面的条件不成立时再判断。"),
    ("哪行可定义一个不接收参数的函数头?", ["function reset():", "def reset():", "def reset:"], 1, "函数定义以 def 开始,参数括号和冒号都要保留。"),
    ("list(range(2, 5)) 的结果是什么?", ["[2, 3, 4, 5]", "[3, 4]", "[2, 3, 4]"], 2, "range 包含起点,排除终点。"),
    ("count 从 3 开始,执行 while count > 0: count -= 1 后还剩多少?", ["0", "1", "3"], 0, "每次迭代递减,条件在 0 时不再成立。"),
    ("type(b'AB').__name__ 是什么?", ["str", "bytes", "list"], 1, "b 前缀构造 bytes 对象。"),
    ("'east gate'.replace('east', 'west') 的结果是什么?", ["east west", "east gate", "west gate"], 2, "replace 返回替换后的新字符串。"),
    ("哪个字面量创建列表?", ["[4, 9]", "{4, 9}", "(4, 9)"], 0, "方括号语法创建列表。"),
    ("哪个表达式创建单元素元组?", ["(4)", "[4]", "(4,)"], 2, "单元素元组需要逗号。"),
    ("哪个字面量表示名称 A 对应数值 2 的字典?", ["{'A' => 2}", "{'A': 2}", "('A', 2)"], 1, "字典用冒号分隔键和值。"),
    ("print(type([])) 显示什么?", ["<class 'list'>", "<class 'tuple'>", "<class 'dict'>"], 0, "type 返回对象所属的类。"),
    ("def idle(): pass 定义后,type(idle()).__name__ 是什么?", ["function", "bool", "NoneType"], 2, "没有显式 return 时,调用返回 None。"),
    ("[0, None, (), [], 3, {}] 有几个顶层元素?", ["4", "6", "7"], 1, "每个空容器也各算一个元素。"),
    ("colors = ['blue', 'amber', 'gray'],colors[1] 是什么?", ["blue", "amber", "gray"], 1, "列表索引从 0 开始。"),
    ("'%.2f' % 8.376 的结果是什么?", ["8.376", "8.37", "8.38"], 2, "这个输入格式化为两位小数。"),
    ("def pause(a, b, c): pass 所定义的函数有几个形参?", ["3", "0", "1"], 0, "pass 不执行操作,形参仍由签名决定。"),
    ("try 中执行 8 / 0,哪个子句可处理该错误?", ["elif ZeroDivisionError:", "except ZeroDivisionError:", "catch ZeroDivisionError:"], 1, "except 指定要捕获的异常类型。"),
    ("已有文本报告,只想读取,open 应选哪个模式?", ["'a'", "'w'", "'r'"], 2, "r 打开文件供读取。"),
    ("已有报告要覆盖写入,哪个模式会在打开时截断旧内容?", ["'w'", "'r'", "'a'"], 0, "w 对已有文件先截断,a 从末尾追加。"),
]


def valid(source):
    try:
        compile(source, "<owned-quiz>", "exec")
    except SyntaxError:
        return False
    return True


def rendered_answers():
    printed = io.StringIO()
    with redirect_stdout(printed):
        print("gate", 7, sep="=")
    assignment = next(value for value in ("$rate = 4", "var rate = 4", "rate = 4") if valid(value))
    token_stream = tokenize.generate_tokens(io.StringIO("level = '#' # audit").readline)
    comment = next(t.string for t in token_stream if t.type == tokenize.COMMENT)
    namespace = {}
    exec("label = '''东门'''\ncount = 6", namespace)
    bad_assignment = next(op for op in ("+=", "~=", "*=") if not valid("total " + op + " 2"))

    class Parcel:
        pass

    data_type = "type(Parcel()) is Parcel" if type(Parcel()) is Parcel and type(Parcel) is type else "unknown"
    condition = next(header for header in ("if mark >= 3:", "if mark => 3:", "if mark >= 3")
                     if valid(header + "\n    pass"))
    branch = {}
    exec("mark = 3\nif mark < 0:\n    name = 'none'\nelif mark == 3:\n    name = 'elif'", branch)
    function = next(head for head in ("function reset():", "def reset():", "def reset:")
                    if valid(head + "\n    pass"))
    sequence = {}
    exec("count = 3\nwhile count > 0:\n    count -= 1", sequence)

    def pause(a, b, c):
        pass

    def idle():
        pass

    try:
        8 / 0
    except ZeroDivisionError:
        error_clause = "except ZeroDivisionError:"
    temp_parent = Path(gettempdir()).resolve()
    with TemporaryDirectory(prefix="mbsky-core-quiz-", dir=temp_parent) as work:
        folder = Path(work).resolve()
        assert folder.parent == temp_parent and folder.name.startswith("mbsky-core-quiz-")
        report = folder / "report.txt"
        report.write_text("old", encoding="utf8")
        with report.open("r", encoding="utf8") as stream:
            read_mode = repr(stream.mode) if stream.read() == "old" else "unexpected"
        with report.open("w", encoding="utf8") as stream:
            write_mode = repr(stream.mode) if report.stat().st_size == 0 else "unexpected"
            stream.write("new")
        assert report.read_text(encoding="utf8") == "new"
    return [
        printed.getvalue().strip(), assignment, comment, type(namespace["label"]).__name__, str(namespace["count"]),
        str(int("17")), bad_assignment, data_type, type(["东门", 4, False]).__name__, str([5, 8, 13][:20]),
        "浮点数 " + str(float("7.25")), condition, branch["name"], function, str(list(range(2, 5))), str(sequence["count"]),
        type(b"AB").__name__, "east gate".replace("east", "west"),
        next(value for value in ("[4, 9]", "{4, 9}", "(4, 9)") if type(ast.literal_eval(value)) is list),
        next(value for value in ("(4)", "[4]", "(4,)") if type(ast.literal_eval(value)) is tuple),
        next(value for value in ("{'A' => 2}", "{'A': 2}", "('A', 2)")
             if valid(value) and type(ast.literal_eval(value)) is dict),
        str(type([])), type(idle()).__name__, str(len([0, None, (), [], 3, {}])),
        ["blue", "amber", "gray"][1], "%.2f" % 8.376,
        str(pause.__code__.co_argcount), error_clause, read_mode, write_mode,
    ]


def main():
    checks = Checks()
    results = rendered_answers()
    for ordinal, ((prompt, options, answer, explanation), actual) in enumerate(zip(QUESTIONS, results, strict=True), 1):
        assert len(set(options)) == len(options)
        checks.eq(f"q{ordinal:02d} owned runtime answer", actual, options[answer])
    checks.finish("python-quiz", runtime=sys.version, questions=len(QUESTIONS),
                  source_scripts_executed=False)


if __name__ == "__main__":
    if sys.argv[1:] == ["--data"]:
        print(json.dumps([dict(prompt=prompt, options=options, answer=answer, explanation=explanation)
                          for prompt, options, answer, explanation in QUESTIONS], ensure_ascii=False))
    else:
        main()
本例需在 本地浏览器 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地浏览器

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

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

下载课程关联工程包:Python

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

下载课程关联工程包:Python

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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