← 返回大綱
第七章

模組與
套件管理

Modules & Package Management

模組

什麼是模組?

模組就是一個 .py 檔案,裡面有可以重複使用的函式和變數。

引入整個模組

import math
print(math.pi)       # 3.14159...
print(math.sqrt(16)) # 4.0
print(math.ceil(3.2)) # 4

只引入需要的部分

from math import pi, sqrt
print(pi)       # 3.14159...
print(sqrt(16)) # 4.0
別名 (alias)

import numpy as np — 用較短的別名,之後就用 np.xxx 呼叫。

內建模組

常用內建模組

模組用途常用功能
math數學運算sqrt, ceil, floor, pi
random隨機數random(), randint(), choice()
datetime日期時間datetime.now(), timedelta
os作業系統getcwd(), listdir(), path.join()
sys系統功能argv, exit(), path
jsonJSON 處理loads(), dumps(), load(), dump()
re正規表達式match(), search(), findall()
內建模組

random 與 datetime 範例

import random
import datetime

# random
print(random.randint(1, 10))         # 1~10 隨機整數
print(random.choice(["頭", "尾"]))   # 隨機選一個
nums = [1, 2, 3, 4, 5]
random.shuffle(nums)                  # 打亂順序
print(nums)

# datetime
now = datetime.datetime.now()
print(now)                           # 2026-05-06 10:30:00
print(now.year, now.month, now.day)  # 2026 5 6
print(now.strftime("%Y/%m/%d"))      # 2026/05/06
自訂模組

建立自己的模組

把常用的函式放在獨立的 .py 檔案裡:

# utils.py
def add(a, b):
    return a + b

def greet(name):
    return f"Hello, {name}!"

PI = 3.14159
# main.py(同個資料夾)
import utils

print(utils.add(3, 5))        # 8
print(utils.greet("Ian"))     # Hello, Ian!
print(utils.PI)               # 3.14159

# 或是
from utils import add, greet
print(add(3, 5))              # 8
pip

pip — 安裝第三方套件

pip 是 Python 的套件管理工具,可以安裝社群開發的套件:

# 安裝套件
pip install requests
pip install pandas numpy matplotlib

# 查看已安裝套件
pip list

# 解除安裝
pip uninstall requests

# 確認某個套件版本
pip show requests
macOS 注意

macOS 可能需要用 pip3 而不是 pip。或在 VS Code 終端機直接用 pip

套件管理

requirements.txt

記錄專案需要的所有套件,方便他人重現環境:

# 產生 requirements.txt
pip freeze > requirements.txt

# requirements.txt 內容範例:
# requests==2.31.0
# pandas==2.1.0
# numpy==1.26.0

# 根據 requirements.txt 安裝所有套件
pip install -r requirements.txt
好習慣

每個專案都應該有 requirements.txt,讓別人(和未來的自己)能快速設定環境。

實作練習

動手試試看

# 猜數字遊戲(使用 random 模組)
import random

def play_game():
    secret = random.randint(1, 100)
    attempts = 0

    print("我想了一個 1~100 的數字,猜猜看!")

    while True:
        guess = int(input("你的猜測:"))
        attempts += 1

        if guess < secret:
            print("太小了!")
        elif guess > secret:
            print("太大了!")
        else:
            print(f"恭喜!答案是 {secret},你猜了 {attempts} 次!")
            break

play_game()

第七章完成!

學會了 import、常用內建模組與 pip 套件管理。