Python常用內置模組:random和time
1. random模組
# 導入random模組
import random
# 生成隨機整數
print(random.randint(1, 10)) # 1到10之間的隨機整數
print(random.randrange(0, 100, 2)) # 0到100之間的隨機偶數
# 生成隨機浮點數
print(random.random()) # 0到1之間的隨機浮點數
print(random.uniform(1.0, 10.0)) # 1到10之間的隨機浮點數
# 序列相關操作
numbers = [1, 2, 3, 4, 5]
print(random.choice(numbers)) # 隨機選擇一個元素
random.shuffle(numbers) # 打亂序列順序
print(random.sample(numbers, 3)) # 隨機選擇3個不重複元素
實際應用示例:
# 模擬擲骰子
def roll_dice():
return random.randint(1, 6)
# 生成隨機密碼
def generate_password(length=8):
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
return ''.join(random.choice(chars) for _ in range(length))
2. time模組
# 導入time模組
import time
# 獲取當前時間戳
print(time.time()) # 自1970年1月1日起的秒數
# 獲取格式化時間
print(time.ctime()) # 當前時間的字符串表示
print(time.strftime("%Y-%m-%d %H:%M:%S")) # 自定義格式
# 程序暫停
time.sleep(1) # 暫停1秒
# 時間轉換
timestamp = time.time()
time_struct = time.localtime(timestamp)
print(time_struct.tm_year) # 獲取年份
print(time_struct.tm_mon) # 獲取月份
實際應用示例:
# 計算程序執行時間
def measure_time():
start = time.time()
# 執行某些操作
time.sleep(2)
end = time.time()
return end - start
# 創建定時器
def countdown(seconds):
while seconds > 0:
print(f"倒計時:{seconds}秒")
time.sleep(1)
seconds -= 1
print("時間到!")
3. 結合使用示例
# 模擬隨機延遲
def random_delay():
delay = random.uniform(0.1, 1.0)
time.sleep(delay)
return delay
# 定時隨機抽獎
def timed_lottery():
while True:
winner = random.choice(['小明', '小華', '小李', '小張'])
print(f"中獎者是:{winner}")
time.sleep(5) # 每5秒抽獎一次
練習題
-
創建一個簡單的猜數字遊戲:
- 生成1-100的隨機數
- 記錄玩家猜測次數和用時
- 提供適當的提示(大了/小了)
-
實現一個簡單的定時提醒工具:
- 允許用戶設置提醒時間
- 到時間後顯示提醒信息
- 支持多個提醒任務
常見錯誤和注意事項
random模組:
- 注意random.randint()的範圍是包含兩端的
- random.randrange()不包含結束值
- 使用random.sample()時注意序列長度
time模組:
- time.sleep()可能不精確
- 注意時區問題
- 長時間運行時注意時間戳溢出
進階應用
# 使用random生成隨機顏色
def random_color():
return '#{:06x}'.format(random.randint(0, 0xFFFFFF))
# 實現簡單的進度條
def progress_bar(total, interval=0.1):
for i in range(total + 1):
progress = '=' * i + ' ' * (total - i)
print(f'r[{progress}] {i}/{total}', end='')
time.sleep(interval)
print()
補充資源
- Python官方文檔中關於random模組的部分
- Python官方文檔中關於time模組的部分
- 更多隨機數生成的應用場景
- 時間處理的最佳實踐