本答案页包含 Python 提示词模板与结构化输出 的 4 道选择题、4 道填空题和 4 道输出预测题,每题都给出准确答案和简短解释。
答案已完整展示,建议先尝试作答,再用本页核对。第一次练习最好从互动练习页开始。
哪个函数可以安全解析 JSON 模型响应?
答案: json.loads
为什么: json.loads 解析 JSON 数据,遇到畸形语法会报错,并且不执行代码。
合法 JSON 能保证响应包含必需字段吗?
答案: 不能,仍然需要校验结构和类型
为什么: JSON 对象可以解析成功,却缺少字段或类型错误。
提示词模板有什么用?
答案: 保持指令稳定,只替换变量部分
为什么: 模板把固定指令和每次请求的数据分开,输出契约也更容易审查。
运行结果是什么?
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])答案: ['minutes']
为什么: 响应包含 title 和 level,但缺少必需的 minutes 键。
补全 JSON 解析调用。
import json
raw = '{"title": "Loops"}'
data = json.____(raw)
print(data["title"])答案: loads
为什么: json.loads 把 JSON 字符串解析成 Python 数据。
补全畸形 JSON 抛出的异常。
import json
try:
json.loads('{"title": "Loops",')
except json.____:
print("invalid json")答案: JSONDecodeError
为什么: 文本不是合法 JSON 时,json.loads 会抛出 JSONDecodeError。
补全缺失键条件。
import json
data = json.loads('{"title": "Loops"}')
required = ["title", "minutes"]
print([key for key in required if key ____ in data])答案: not
为什么: 推导式保留不出现在响应中的键。
补全字典迭代方法。
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 生成键值对,便于逐个检查期望类型。
这段程序打印出什么?
import json
raw = '{"title": "Loops", "level": "beginner"}'
data = json.loads(raw)
print(data["title"])答案: Loops
为什么: title 字段被解析为字符串 Loops。
代码的输出结果是什么?
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。
屏幕上会显示什么?
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,所以出现在类型错误列表中。
这段代码会输出什么?
import json
try:
json.loads('{"title": "Loops",')
except json.JSONDecodeError:
print("invalid json")答案: invalid json
为什么: 末尾的逗号让 JSON 对象不完整,因此解析安全失败。
先试一遍题目
打开 Python 提示词模板与结构化输出 练习页,用即时反馈回答同样的 12 道题。