答案页 · 12 道题

Python 提示词模板与结构化输出练习答案

本页汇总 Python 提示词模板与结构化输出 的 12 道练习。先做练习页,再回到这里核对准确答案和原因。

快速答案

本答案页包含 Python 提示词模板与结构化输出 的 4 道选择题、4 道填空题和 4 道输出预测题,每题都给出准确答案和简短解释。

答案已完整展示,建议先尝试作答,再用本页核对。第一次练习最好从互动练习页开始。

01 · 选择题

哪个函数可以安全解析 JSON 模型响应?

  1. eval
  2. 只用 str.strip
  3. exec
  4. json.loads正确答案

答案: json.loads

为什么: json.loads 解析 JSON 数据,遇到畸形语法会报错,并且不执行代码。

02 · 选择题

合法 JSON 能保证响应包含必需字段吗?

  1. 能,每个 JSON 对象都有 title 和 minutes
  2. 能,JSON 语法证明了结构
  3. 不能,仍然需要校验结构和类型正确答案
  4. 只有响应很短时才行

答案: 不能,仍然需要校验结构和类型

为什么: JSON 对象可以解析成功,却缺少字段或类型错误。

03 · 选择题

提示词模板有什么用?

  1. 保证模型正确
  2. 加密 API 密钥
  3. 不再需要校验输出
  4. 保持指令稳定,只替换变量部分正确答案

答案: 保持指令稳定,只替换变量部分

为什么: 模板把固定指令和每次请求的数据分开,输出契约也更容易审查。

04 · 选择题

运行结果是什么?

import json
raw = '{"title": "Loops", "level": "beginner"}'
data = json.loads(raw)
required = ["title", "level", "minutes"]
print([key for key in required if key not in data])
  1. ['minutes']正确答案
  2. []
  3. ['title']
  4. ['title', 'level']

答案: ['minutes']

为什么: 响应包含 title 和 level,但缺少必需的 minutes 键。

05 · 填空题

补全 JSON 解析调用。

import json
raw = '{"title": "Loops"}'
data = json.____(raw)
print(data["title"])

答案: loads

为什么: json.loads 把 JSON 字符串解析成 Python 数据。

06 · 填空题

补全畸形 JSON 抛出的异常。

import json
try:
    json.loads('{"title": "Loops",')
except json.____:
    print("invalid json")

答案: JSONDecodeError

为什么: 文本不是合法 JSON 时,json.loads 会抛出 JSONDecodeError。

07 · 填空题

补全缺失键条件。

import json
data = json.loads('{"title": "Loops"}')
required = ["title", "minutes"]
print([key for key in required if key ____ in data])

答案: not

为什么: 推导式保留不出现在响应中的键。

08 · 填空题

补全字典迭代方法。

required = {"title": str, "minutes": int}
data = {"title": "Loops", "minutes": "12"}
wrong = [key for key, kind in required.____() if not isinstance(data[key], kind)]
print(wrong)

答案: items

为什么: items 生成键值对,便于逐个检查期望类型。

09 · 输出预测

这段程序打印出什么?

import json
raw = '{"title": "Loops", "level": "beginner"}'
data = json.loads(raw)
print(data["title"])

答案: Loops

为什么: title 字段被解析为字符串 Loops。

10 · 输出预测

代码的输出结果是什么?

import json
raw = '{"title": "Loops"}'
data = json.loads(raw)
required = ["title", "minutes"]
print([key for key in required if key not in data])

答案: ['minutes']

为什么: 只有 minutes 缺失,所以列表中包含 minutes。

11 · 输出预测

屏幕上会显示什么?

required = {"title": str, "minutes": int}
data = {"title": "Loops", "minutes": "12"}
print([key for key, kind in required.items() if not isinstance(data[key], kind)])

答案: ['minutes']

为什么: minutes 是字符串而不是 int,所以出现在类型错误列表中。

12 · 输出预测

这段代码会输出什么?

import json
try:
    json.loads('{"title": "Loops",')
except json.JSONDecodeError:
    print("invalid json")

答案: invalid json

为什么: 末尾的逗号让 JSON 对象不完整,因此解析安全失败。

先试一遍题目

打开 Python 提示词模板与结构化输出 练习页,用即时反馈回答同样的 12 道题。

练习本课