答案頁 · 12 道題

Python 提示詞模板與結構化輸出練習答案

本頁彙整 Python 提示詞模板與結構化輸出 的 12 道練習。先做練習頁,再回到這裡核對準確答案和原因。

快速答案

本答案頁包含 Python 提示詞模板與結構化輸出 的 4 道選擇題、4 道填空題和 4 道輸出預測題,每題都給出準確答案和簡短解釋。

答案已完整展示,建議先嘗試作答,再用本頁核對。第一次練習最好從互動練習頁開始。

01 · 選擇題

哪個函式可以安全解析 JSON 模型回應?

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

答案: json.loads

為什麼: json.loads 解析 JSON 資料,遇到畸形語法會報錯,並且不執行程式碼。

02 · 選擇題

合法 JSON 能保證回應包含必需欄位嗎?

  1. 能,JSON 語法證明了結構
  2. 不能,仍然需要驗證結構和型別正確答案
  3. 能,每個 JSON 物件都有 title 和 minutes
  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. ['title']
  3. ['title', 'level']
  4. []

答案: ['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 道題。

練習本課