Python 模組和匯入
模組就是一個 .py 檔案;用 import math 引入後寫 math.sqrt(),或者 from math import sqrt 直接用 sqrt()。
模組就是一個裝著 Python 程式碼、能給別的程式用的檔案。Python 自帶幾百個,合起來叫標準庫:算數學、處理日期、讀寫檔案、隨機數……早就有人寫好、測好了。第 3 課已經見過一個:
1import math2 3print(math.sqrt(16))4print(math.pi)5print(math.ceil(7 / 3))
4.0 3.141592653589793 3
import math 把模組載入一次,給你一個名字 math。裡面的東西都用點來拿:math.sqrt、math.pi。import 寫在檔案最上面,讀程式碼的人一眼就能看出程式用了哪些模組。
import
可以一行匯入好幾個模組,比如 import math, statistics,也可以一行一個(更常見)。比如用 statistics 算一組數常用的幾種平均:
1import statistics2 3ore = [12, 7, 9, 12, 5]4print(statistics.mean(ore))5print(statistics.median(ore))6print(statistics.mode(ore))
9 9 12
| 函式 | 返回 |
|---|---|
mean | 平均數:總和除以個數 |
median | 中位數:排好序以後中間那個 |
mode | 眾數:出現次數最多的那個 |
前面帶著模組名,意思很清楚:statistics.mean 不會和你自己寫的 mean 函式搞混。
這段會顯示什麼?
1import statistics2 3print(statistics.median([3, 1, 9]))
median 先排好序:1、3、9,中間那個是 3。4.333333333333333 是平均數 mean 的結果。平均數和中位數
✓用 statistics 模組,先顯示燈亮的小時數的平均數,再顯示中位數。
8 7
1hours = [6, 9, 7, 12, 6]from、import 和 as
from 模組 import 名字 只把這個名字拿進來,用的時候不用再寫模組名和點。as 給模組或名字起一個更短、更清楚的名字。
1from math import sqrt, pi2import statistics as stats3import datetime as dt4 5print(sqrt(81))6print(round(pi, 2))7print(stats.mean([2, 4, 9]))8print(dt.date(2026, 11, 1))
9.0 3.14 5 2026-11-01
| 這樣寫 | 之後這樣用 |
|---|---|
import math | math.sqrt(9) |
from math import sqrt | sqrt(9) |
import statistics as stats | stats.mean(...) |
from math import * | math 裡所有的名字,不用字首;最好別用,看不出一個名字是從哪來的 |
會怎麼樣?
1import math2 3print(math.ceil(2.5))4print(ceil(4.2))
import math 給你的是 math 這個名字,不是它裡面的名字。第一個 print 沒問題;第二個碰到不認識的名字 ceil,停了。要寫 math.ceil,或者再加一句 from math import ceil。補上名字,讓最後一行不用寫 math. 也能用。
1from math import 2 3print(sqrt(25))
from math import sqrt 只把 sqrt 這個名字拿進來,之後直接寫 sqrt(25)。幾個好用的模組
| 模組 | 幹什麼用 | 例子 |
|---|---|---|
random | 隨機數、隨機挑 | random.randint(1, 6) |
statistics | 平均數和離散程度 | statistics.median(xs) |
collections | 更多容器:Counter、defaultdict、deque、namedtuple | Counter(words) |
string | 現成的字母、數字、標點字串 | string.digits |
time | 時鐘,還有等一會兒 | time.sleep(1) |
math | 開平方、向上向下取整、圓周率 | math.floor(2.7) |
random 每次執行挑出來的都不一樣,所以這裡只檢查結果是什麼樣的。多執行幾次:背後的數在變,顯示的結果不變。
1import random2 3roll = random.randint(1, 6)4print(1 <= roll <= 6)5lamp = random.choice(["榆樹街", "橡樹巷", "磨坊路"])6print(lamp in ["榆樹街", "橡樹巷", "磨坊路"])7rolls = [random.randint(1, 6) for i in range(10)]8print(len(rolls))9print(min(rolls) >= 1 and max(rolls) <= 6)
True True 10 True
randint(a, b) 給一個從 a 到 b 的整數,兩頭都包括;choice 從列表裡挑一個。這個模組裡還有別的,比如把列表打亂的 shuffle。
random.randint(1, 3) 可能給出哪些數?(可以選好幾個)
randint 的兩頭都包括,所以 1、2、3 都可能出現;0 和 4 在範圍外面。這一點和 range(1, 3) 不一樣。collections:計數和分組
collections 模組裡有幾種更好用的容器。計數、分組的時候,用它們能省不少事:
1from collections import Counter, defaultdict2 3loads = ["礦石", "燈油", "礦石", "燈芯", "礦石", "燈油"]4counts = Counter(loads)5print(counts["礦石"])6print(counts.most_common(2))7 8by_letter = defaultdict(list)9for item in ["oak", "elm", "oil", "ash"]:10 by_letter[item[0]].append(item)11print(dict(by_letter))
3
[('礦石', 3), ('燈油', 2)]
{'o': ['oak', 'oil'], 'e': ['elm'], 'a': ['ash']}
Counter 幫你數數,就像第 11 課用字典計數的那個迴圈。defaultdict(list) 碰到沒見過的鍵,自動給一個空列表,所以可以直接 append。
這段會顯示什麼?
1from collections import Counter2 3c = Counter("banana")4print(c["a"], c.most_common(1))
Counter("banana") 數每個字母:a 有 3 個,n 有 2 個,b 有 1 個。most_common(1) 給出最多的那一個和它的次數,放在列表裡。前兩名
✓用 from ... import 匯入 Counter,數一數送來的貨,顯示最多的兩種和它們的次數。
[('礦石', 3), ('燈油', 2)]1deliveries = ["燈油", "礦石", "燈芯", "礦石", "燈油", "礦石", "玻璃"]string 和 time
string 模組裡放著現成的字母表、數字和標點,time 模組管時鐘:
1import string2import time3 4print(string.ascii_uppercase)5print(string.digits)6code = "LAMP42"7print(all([c in string.ascii_uppercase + string.digits for c in code]))8 9start = time.time()10total = sum(range(100000))11print(time.time() - start >= 0)
ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 True True
time.time() 是從 1970 年起到現在的秒數,每時每刻都在變。幹活之前取一次,幹完再取一次,差就是這活花了多久;第 25 課再多講時間。all([...]) 在列表裡每一項都為真時給出 True。
這段會顯示什麼?
1import string2 3print(string.digits[:3], len(string.ascii_lowercase))
string.digits 是 "0123456789",取前 3 個是 012;ascii_lowercase 是 26 個小寫字母。缺了哪些字母
✓按字母表順序,把 sign 裡沒出現的字母連成一個詞顯示出來。用 string.ascii_lowercase。
dg
1sign = "the quick brown fox jumps over the lazy cat"看看模組裡有什麼
在你自己的電腦上,Python 的互動模式(在終端裡輸入 python)能告訴你。dir() 列出模組裡的名字,help() 說明其中一個是幹什麼的:
1import math2dir(math) # ['acos', 'ceil', 'floor', 'pi', 'sqrt', ...]3help(math.ceil) # ceil(x, /) Return the ceiling of x ...
這兩個在這裡的瀏覽器例子裡用不了。另一個地方是官方文件 docs.python.org,標準庫裡每個模組都有一頁。
在自己電腦上,想列出 math 模組裡有哪些名字,用哪個?
dir(模組) 列出模組裡所有的名字。模組不能直接放進 list(),也沒有 names() 這個方法。自己寫模組
任何一個 .py 檔案都是模組。程式越寫越長,就拆成幾個檔案,用檔名(不帶 .py)從一個檔案匯入另一個。比如你電腦上的同一個資料夾裡有這兩個檔案:
1PRICE = 42 3def cost(count):4 return count * PRICE5 6def label(street):7 return street + "的燈"
1import lamps2from lamps import label3 4print(lamps.cost(3))5print(label("榆樹街"))
執行 main.py,Python 在旁邊找到 lamps.py,把它跑一次,裡面的名字就能用了:
import lampslamps.cost(3)$ python main.py 12 榆樹街的燈
這一頁的例子都是各跑各的,匯入不了你自己的檔案;這個請在自己電腦上試。檔名別和標準模組重名(random.py、math.py):Python 會匯入你的檔案,而不是真正的那個模組。
你在自己的資料夾裡放了一個 random.py,然後在同一個資料夾的程式裡寫 import random。匯入的是哪一個?
random.py 就用它了,真正的 random 模組被擋住。所以檔名別和標準模組重名。if __name__ == "__main__"
每個模組都有一個變數叫 __name__。在你執行的那個檔案裡,它是 "__main__";在被匯入的檔案裡,它是模組名,比如 "lamps"。這樣一個檔案就能做到:直接執行時做一件事,被匯入時做另一件事。
1def cost(count):2 return count * 43 4def main():5 print(f"測試 cost:{cost(3)}")6 7print(__name__)8if __name__ == "__main__":9 main()
__main__ 測試 cost:12
直接執行這個檔案,main() 就會跑。要是 main.py 用 import 匯入它,__name__ 就是它的模組名,if 不成立,只定義了幾個函式,不會顯示測試結果。所以 if __name__ == "__main__": 下面放的,是隻有這個檔案自己當程式跑時才該跑的程式碼。
- 檔案從頭開始跑 → __name__ == "__main__"?
- __name__ == "__main__"? → main() 跑 (直接執行)
- __name__ == "__main__"? → 只定義了函式 (被 import)
lamps.py 的最後寫著 if __name__ == "__main__":,裡面呼叫 main()。另一個檔案 import lamps 時,main() 會跑嗎?
__name__ 是它的模組名,不是 "__main__",所以 if 不成立,main() 不跑。只有直接執行 lamps.py 時它才跑。安裝第三方包
標準庫以外,Python 包索引(PyPI)上還有成千上萬個別人寫的包。在自己電腦上,用 pip 安裝一個,在終端裡敲,不是在 Python 裡:
$ pip install requests Successfully installed requests
裝好以後,import requests 就和別的模組一樣用。有的系統上叫 pip3,或者寫成 python -m pip。這裡的瀏覽器例子裝不了包;這門課用到的都在標準庫裡。
pip install requests 應該在哪裡輸入?
pip 是裝包的工具,在終端裡執行,不是 Python 程式碼。裝好以後,程式裡才用 import requests。這一課學會了
import 模組載入一個模組;用點拿裡面的名字,比如math.sqrt。from 模組 import 名字只拿進這一個名字;as給模組或名字改名。- 標準庫裡有
random、statistics、collections、string、time這些模組;dir()、help()和 docs.python.org 能看裡面有什麼。 - 任何
.py檔案都是模組,用名字就能匯入;if __name__ == "__main__":下面的程式碼只在直接執行這個檔案時才跑。 - 在終端裡
pip install 名字,從 PyPI 安裝包。