常用的 random 函數
函數 功能說明 範例
random.random() 回傳 0~1 之間的亂數 (float) 0.123456789
random.randint(a, b) 回傳整數亂數(包含 a 和 b) random.randint(1, 6) → 骰子
random.choice (列表) 從列表中隨機選一個元素 random.choice(['蘋果','香蕉'])
random.choices (列表) 從列表中隨機選一個元素 random.choice(['蘋果','香蕉'])
random.shuffle (列表) 將列表隨機洗牌 會改變原本列表內容
random.sample (列表, 數量) 從列表中隨機抽取不重複元素 random.sample([1,2,3,4], 2)
random.uniform() 很實用的函式,用來產生「浮點數」的隨機值, random.uniform(a, b)
適合用在模擬溫度、時間、機率等等更精細的數值。
random.uniform(起始值, 結束值)這個函式會傳回 a 到 b 之間的浮點數亂數(包含 a 與 b),不一定是整數。
import random
dice = random.randint(1, 6)
print("你擲出了:", dice)
import random
names = ["小明", "小美", "小強", "小華"]
winner = random.choice(names)
print("今天的幸運兒是:", winner)
import random
deck = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
random.shuffle(deck)
print("洗牌後的牌堆:", deck)
import random
temperature = random.uniform(20.0, 30.0)
print("目前溫度:", round(temperature, 2), "°C")
#說明:round(temperature, 2) 是把結果四捨五入到小數第 2 位,讓畫面更好看
import random
roi = random.uniform(-0.1, 0.1)
print("本月投資報酬率:", round(roi * 100, 2), "%")
import random as rnd 是 給模組取暱稱(別名) 的寫法,讓你在使用的時候不用一直打完整名稱 random,可以直接用 rnd 替代。
import 模組名稱 as 別名
範例:
import random as rnd
這代表你現在可以用 rnd 來代表 random,效果完全一樣,但寫起來更短更方便。
import random as rnd
print(rnd.randint(1, 10)) # 1~10 的隨機整數
print(rnd.uniform(0, 1)) # 0~1 的隨機浮點數
print(rnd.choice(['A', 'B', 'C'])) # 隨機選一個字母
✅ 節省打字時間(例如:常用的模組 numpy 通常取名為 np,pandas 通常叫 pd)
✅ 避免跟你自己的變數名稱衝突
✅ 讓程式碼看起來更乾淨
寫法 說明
import random
正常使用 random 模組
import random as rnd
使用 rnd 當作別名