模組與套件#

模組(Module) 就是一個 .py 檔案,裡面包含函式、類別和變數,可以被其他程式匯入使用。 套件(Package) 則是包含多個模組的資料夾。


匯入模組#

import 整個模組#

1
2
3
4
5
6
import math

print(math.sqrt(16))   # 4.0
print(math.pi)         # 3.141592653589793
print(math.ceil(3.2))  # 4
print(math.floor(3.9)) # 3

from ... import 指定匯入#

1
2
3
4
5
from math import sqrt, pi

print(sqrt(25))  # 5.0
print(pi)        # 3.141592653589793
# 不需要 math. 前綴

匯入並取別名(as)#

1
2
3
4
5
import numpy as np          # 慣例別名
import pandas as pd         # 慣例別名

import datetime as dt
print(dt.date.today())

常用標準函式庫#

math:數學運算#

1
2
3
4
5
6
7
8
9
import math

print(math.sqrt(2))      # 1.4142...(平方根)
print(math.log(100, 10)) # 2.0(log10(100))
print(math.log(math.e))  # 1.0(自然對數)
print(math.sin(math.pi / 2))  # 1.0
print(math.factorial(5)) # 120
print(math.gcd(48, 18))  # 6(最大公因數)
print(math.inf)           # inf(無限大)

random:隨機數#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import random

# 隨機整數
print(random.randint(1, 100))   # 1 到 100 的隨機整數

# 隨機浮點數
print(random.random())           # 0.0 到 1.0 之間

# 從串列隨機選一個
fruits = ["apple", "banana", "cherry"]
print(random.choice(fruits))

# 從串列隨機選 n 個(不重複)
print(random.sample(fruits, 2))

# 打亂串列順序(原地修改)
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(numbers)

# 設定隨機種子(讓結果可重現)
random.seed(42)
print(random.randint(1, 100))  # 每次都是同一個結果

datetime:日期與時間#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from datetime import datetime, date, timedelta

# 現在時間
now = datetime.now()
print(now)                        # 2026-04-11 15:30:00.123456
print(now.year, now.month, now.day)   # 2026 4 11
print(now.hour, now.minute, now.second)  # 15 30 0

# 格式化輸出
print(now.strftime("%Y-%m-%d"))       # 2026-04-11
print(now.strftime("%Y/%m/%d %H:%M")) # 2026/04/11 15:30

# 解析字串為 datetime
d = datetime.strptime("2026-01-01", "%Y-%m-%d")
print(d)  # 2026-01-01 00:00:00

# 日期計算
today = date.today()
delta = timedelta(days=30)
future = today + delta
print(f"30 天後:{future}")

# 計算兩個日期的差距
start = date(2026, 1, 1)
end = date(2026, 4, 11)
diff = end - start
print(f"相差 {diff.days} 天")  # 相差 100 天

os:作業系統操作#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import os

# 取得當前目錄
print(os.getcwd())

# 路徑操作
path = os.path.join("folder", "subfolder", "file.txt")
print(path)  # folder/subfolder/file.txt(依系統格式)

print(os.path.exists("file.txt"))     # 檔案是否存在
print(os.path.isfile("file.txt"))     # 是否為檔案
print(os.path.isdir("folder"))        # 是否為資料夾
print(os.path.basename("/path/file.txt"))  # file.txt
print(os.path.dirname("/path/file.txt"))   # /path

# 取得環境變數
home = os.environ.get("HOME", "未設定")
print(home)

json:JSON 資料處理#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import json

# Python 物件轉 JSON 字串
data = {"name": "Alice", "age": 25, "scores": [85, 92, 78]}
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)

# JSON 字串轉 Python 物件
json_data = '{"name": "Bob", "age": 30}'
obj = json.loads(json_data)
print(obj["name"])  # Bob

# 寫入 JSON 檔案
with open("data.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

# 讀取 JSON 檔案
with open("data.json", "r", encoding="utf-8") as f:
    loaded = json.load(f)
print(loaded)

collections:進階資料結構#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from collections import Counter, defaultdict, deque

# Counter:計數
text = "hello world"
count = Counter(text)
print(count)              # Counter({'l': 3, 'o': 2, ...})
print(count.most_common(3))  # 出現最多的 3 個

words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
word_count = Counter(words)
print(word_count)  # Counter({'apple': 3, 'banana': 2, 'cherry': 1})

# defaultdict:帶預設值的字典
dd = defaultdict(list)
dd["fruits"].append("apple")
dd["fruits"].append("banana")
dd["vegs"].append("carrot")
print(dict(dd))  # {'fruits': ['apple', 'banana'], 'vegs': ['carrot']}

# deque:雙端佇列(兩端都可以快速增刪)
d = deque([1, 2, 3])
d.appendleft(0)
d.append(4)
print(d)           # deque([0, 1, 2, 3, 4])
d.popleft()
print(d)           # deque([1, 2, 3, 4])

建立自己的模組#

建立 myutils.py

1
2
3
4
5
6
7
8
9
# myutils.py

def celsius_to_fahrenheit(c):
    return c * 9 / 5 + 32

def is_even(n):
    return n % 2 == 0

PI = 3.14159

在其他檔案匯入:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# main.py(與 myutils.py 在同一個資料夾)
import myutils

print(myutils.celsius_to_fahrenheit(100))  # 212.0
print(myutils.is_even(4))                  # True
print(myutils.PI)                          # 3.14159

# 或用 from 匯入
from myutils import celsius_to_fahrenheit
print(celsius_to_fahrenheit(0))            # 32.0

安裝第三方套件(pip)#

Python 的套件管理工具是 pip

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# 安裝套件
pip install requests
pip install pandas

# 安裝指定版本
pip install requests==2.31.0

# 查看已安裝的套件
pip list

# 匯出套件清單(方便分享專案)
pip freeze > requirements.txt

# 從清單安裝所有套件
pip install -r requirements.txt

# 解除安裝
pip uninstall requests

常用第三方套件#

套件用途
requestsHTTP 請求(爬蟲、API)
pandas資料分析
numpy數值運算
matplotlib資料視覺化
beautifulsoup4HTML 解析
fastapi快速 API 開發
sqlalchemy資料庫 ORM