本答案頁包含 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 道題。