6.2 常用标准库
Python 自带的模块统称标准库,号称"自带电池"。本节介绍几个新手最常用的。
random:随机数
import random
print(random.randint(1, 10)) # 1~10 的随机整数(两端都包含)
print(random.random()) # 0~1 的随机小数
print(random.choice(["石头", "剪刀", "布"])) # 从列表随机选一个
nums = [1, 2, 3, 4, 5]
random.shuffle(nums) # 打乱列表顺序
print(nums)
print(random.sample(range(1, 34), 6)) # 从 1~33 随机抽 6 个不重复的(买彩票?)
第 10 章的猜数字游戏就靠 random.randint()。
datetime:日期时间
from datetime import datetime, timedelta
now = datetime.now()
print(now) # 2026-07-26 15:30:45.123456
print(now.year, now.month, now.day) # 2026 7 26
# 格式化输出
print(now.strftime("%Y-%m-%d %H:%M:%S")) # 2026-07-26 15:30:45
print(now.strftime("%Y年%m月%d日")) # 2026年07月26日
# 日期计算
tomorrow = now + timedelta(days=1)
print(tomorrow.strftime("%Y-%m-%d")) # 明天的日期
# 字符串转日期
day = datetime.strptime("2026-01-01", "%Y-%m-%d")
print((now - day).days) # 距离元旦过了多少天
time:暂停与计时
import time
print("3 秒后启动...")
time.sleep(3) # 程序暂停 3 秒
print("启动!")
start = time.time() # 当前时间戳(秒数)
# ...做一些事...
print(f"耗时 {time.time() - start:.2f} 秒")
os:和操作系统打交道
import os
print(os.getcwd()) # 当前工作目录
print(os.listdir(".")) # 列出当前目录下的所有文件
os.makedirs("data", exist_ok=True) # 创建文件夹(已存在也不报错)
print(os.path.exists("data")) # 判断文件/文件夹是否存在
小例子:石头剪刀布
用 random 写个小游戏:
import random
choices = ["石头", "剪刀", "布"]
computer = random.choice(choices)
player = input("出拳(石头/剪刀/布):")
print(f"电脑出了:{computer}")
if player == computer:
print("平局!")
elif (player == "石头" and computer == "剪刀") or \
(player == "剪刀" and computer == "布") or \
(player == "布" and computer == "石头"):
print("你赢了!")
else:
print("你输了!")
💡 行尾的
\表示"这一行没写完,下一行继续",用于拆分过长的代码行。
练习
- 模拟掷骰子 10 次,打印每次的点数,最后打印其中的最大点数。
- 打印你出生那天到今天一共过了多少天(用
datetime.strptime解析你的生日)。 - 写一个倒计时程序:从 5 数到 1,每秒打印一个数,最后打印"发射!🚀"。
点击查看答案
# 1
import random
results = []
for i in range(10):
dice = random.randint(1, 6)
results.append(dice)
print(dice)
print("最大点数:", max(results))
# 2
from datetime import datetime
birthday = datetime.strptime("2008-05-20", "%Y-%m-%d")
days = (datetime.now() - birthday).days
print(f"你已经活了 {days} 天")
# 3
import time
for i in range(5, 0, -1):
print(i)
time.sleep(1)
print("发射!🚀")
本章小结
random:随机整数、随机选择、打乱顺序datetime:获取时间、格式化、日期加减time.sleep():暂停程序os:文件夹相关操作
下一节:6.3 pip 与第三方库