模組(Module)就是一個 Python 檔案,裡面封裝了可以重複使用的函式、變數、類別。
好處:
import math # 匯入整個模組
import math as m # 匯入並改別名
from math import sqrt # 從模組匯入特定函式
from math import * # 匯入模組內所有名稱
import math
print(math.sqrt(16)) # 平方根
print(math.pow(2, 3)) # 次方
print(math.ceil(4.3)) # 無條件進位
print(math.floor(4.9)) # 無條件捨去
print(math.pi) # 圓周率
random 模組是用來產生隨機數字或隨機選取資料的工具。
功能:產生整數,範圍從 a 到 b (包含 a 和 b)。
import random
print(random.randint(1, 10)) # 可能輸出 1~10 的任何一個整數
功能:產生浮點數,範圍從 a 到 b(可以有小數)。
import random
print(random.uniform(1, 5)) # 可能輸出 1.23, 3.78, 4.99 等
功能:從一個序列(列表、字串、元組等)中隨機取出 1 個元素。
import random
letters = ['a', 'b', 'c']
print(random.choice(letters)) # 可能輸出 'a' 或 'b' 或 'c'
功能:從序列中隨機取出 k 個不重複的元素。
import random
numbers = list(range(10)) # [0, 1, 2, ..., 9]
print(random.sample(numbers, 3)) # 可能輸出 [2, 8, 5](順序也會變)
功能:直接打亂原本序列的順序(沒有回傳值)。
import random
cards = [1, 2, 3, 4, 5]
random.shuffle(cards)
print(cards) # 順序可能變成 [3, 5, 1, 4, 2]
import random
import string
# 1. 從 1~100 隨機抽一個數字
print("隨機整數:", random.randint(1, 100))
# 2. 從 0~1 隨機小數
print("隨機小數:", random.uniform(0, 1))
# 3. 從字母中隨機選 1 個
print("隨機字母:", random.choice(string.ascii_letters))
# 4. 從數字 0~9 中隨機抽 5 個不重複的數字
print("不重複抽取:", random.sample(range(10), 5))
# 5. 洗牌
cards = list(range(1, 6))
random.shuffle(cards)
print("洗牌後:", cards)
明天要做一個小挑戰:製作隨機密碼產生器!
結合今天的 random 模組與前面學過的字串操作,挑戰製作一個可自訂長度與字符種類的隨機密碼產生器,並確保密碼同時包含大小寫字母、數字與符號!