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
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 |
json | JSON 處理 | loads(), dumps(), load(), dump() |
re | 正規表達式 | match(), search(), findall() |
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 是 Python 的套件管理工具,可以安裝社群開發的套件:
# 安裝套件
pip install requests
pip install pandas numpy matplotlib
# 查看已安裝套件
pip list
# 解除安裝
pip uninstall requests
# 確認某個套件版本
pip show requests
macOS 可能需要用 pip3 而不是 pip。或在 VS Code 終端機直接用 pip。
記錄專案需要的所有套件,方便他人重現環境:
# 產生 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 套件管理。