答案頁 · 12 道題

Python 模組與匯入練習答案

本頁彙整 Python 模組與匯入 的 12 道練習。先做練習頁,再回到這裡核對準確答案和原因。

快速答案

本答案頁包含 Python 模組與匯入 的 4 道選擇題、4 道填空題和 4 道輸出預測題,每題都給出準確答案和簡短解釋。

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

01 · 選擇題

import math 會做什麼?

  1. 載入 math 模組供使用正確答案
  2. 把 math 重命名為 module
  3. 列印 math 裡的所有函式
  4. 從網際網路安裝 math

答案: 載入 math 模組供使用

為什麼: import 語句讓模組裡的名字可以通過 math 命名空間存取。

02 · 選擇題

螢幕上會顯示什麼?

import math
print(math.floor(3.8))
  1. 3.8
  2. 8
  3. 4
  4. 3正確答案

答案: 3

為什麼: math.floor 會向下取整到最接近的整數。

03 · 選擇題

哪一行只從 math 匯入 sqrt?

  1. import math as sqrt
  2. from sqrt import math
  3. from math import sqrt正確答案
  4. import math.sqrt

答案: from math import sqrt

為什麼: from-import 會把一個名字帶入目前命名空間。

04 · 選擇題

這段程式碼會輸出什麼?

import statistics as stats
print(stats.mean([2, 4, 6]))
  1. 6
  2. 2
  3. 4正確答案
  4. 12

答案: 4

為什麼: 別名 stats 指向 statistics 模組,mean([2, 4, 6]) 的結果是 4。

05 · 填空題

補全匯入語句。

____ math
print(math.ceil(2.1))

答案: import

為什麼: import math 會先載入模組,然後才能呼叫 math.ceil。

06 · 填空題

補全 from-import,使 sqrt 可用。

from math ____ sqrt
print(sqrt(25))

答案: import

為什麼: 語法是 from module import name。

07 · 填空題

補全 random 模組的別名。

import random ____ rnd
print(rnd.randint(1, 1))

答案: as

為什麼: import random as rnd 讓模組可以通過更短的名字 rnd 存取。

08 · 填空題

補全計算平平均值的 statistics 呼叫。

import statistics
print(statistics.____([2, 4, 6]))

答案: mean

為什麼: statistics.mean 回傳這些值的算術平平均值。

09 · 輸出預測

執行結果是什麼?

import math
print(math.sqrt(64))

答案: 8.0

為什麼: 64 的平方根是 8.0,sqrt 回傳浮點數。

10 · 輸出預測

這段程式列印出什麼?

from math import pow
print(pow(2, 3))

答案: 8.0

為什麼: pow(2, 3) 表示 2 的 3 次方,結果是 8.0。

11 · 輸出預測

程式碼的輸出結果是什麼?

import math
print(math.ceil(4.2))

答案: 5

為什麼: ceil 向上取整,所以 4.2 變成 5。

12 · 輸出預測

螢幕上會顯示什麼?

from statistics import mean
print(mean([2, 4, 6]))

答案: 4

為什麼: 總和是 12,一共有 3 個值,所以平平均值是 4。

先試一遍題目

打開 Python 模組與匯入 練習頁,用即時回饋回答同樣的 12 道題。

練習本課