最近学习Python课程,使用到了 Python 内置的 random 模块,接触到一些实用、有趣的例子。
import randomparticipants = ["关羽", "张飞", "赵云", "刘备", "黄盖"]winner = random.choice(participants) # 单个随机元素print(f"幸运用户:{winner}")# 抽取多个不重复的幸运用户(不放回抽样)lucky_three = random.sample(participants, k=3)print(f"三等奖:{lucky_three}")解释:choice() 适用于单次抽取;sample() 保证不重复,用于获奖名单、随机分配任务等。若要依次抽取多个可使用choices()(注意这个方法和sample()的区别是可能有重复,是有放回抽样)。代码实现中还可以借助random模块使用组成姓名的”姓“和”名“的列表,随机生成一些不同的名字。
cards = ["A♠", "K♥", "Q♣", "J♦", "10♠"]random.shuffle(cards)print(f"洗牌后:{cards}")解释:shuffle() 原地打乱列表,常用于游戏发牌、考试题目乱序、A/B测试分组。可以自己动手写一个斗地主随机发牌的程序,先生成牌,然后打乱,最后发牌。
import randomimport stringdefgenerate_password(length=12, use_digits=True, use_punctuation=True): chars = string.ascii_letters # 大小写字母if use_digits: chars += string.digitsif use_punctuation: chars += string.punctuation# 随机选 length 个字符(允许重复) password = ''.join(random.choices(chars, k=length))return passwordprint(f"随机密码:{generate_password()}")# 输出示例: "tK$9m#R!zL@p"解释:choices() 可重复取样,适合生成高熵密码。可关闭数字或标点来满足不同网站规则。
import timeimport randomdeffetch_data(url): delay = random.uniform(0.5, 2.5) # 随机 0.5~2.5 秒延迟 time.sleep(delay) print(f"请求 {url} 完成,耗时 {delay:.2f} 秒")# ... 实际请求代码fetch_data("https://www.baidu.com/")解释:uniform(a, b) 生成浮点数延迟,让请求间隔不规律,更接近真人行为,也避免服务端频率限制。
import randomdefestimate_pi(num_points=1000000): inside = 0for _ in range(num_points): x, y = random.random(), random.random() # 0~1 之间的点if x*x + y*y <= 1: # 落在单位圆内 inside += 1return (inside / num_points) * 4pi_approx = estimate_pi(1_000_000)print(f"估算π值:{pi_approx} (误差:{pi_approx - 3.14159265:.6f})")解释:利用随机点落在正方形内切圆的概率 = π/4。点越多越逼近 π。这是概率论和数值模拟的经典趣味演示。说实话这个我理解起来有点费劲了
import randomimport matplotlib.pyplot as pltdefrandom_walk(steps=1000): x, y = 0, 0 x_coords, y_coords = [0], [0]for _ in range(steps): direction = random.choice(['N','S','E','W'])if direction == 'N': y += 1elif direction == 'S': y -= 1elif direction == 'E': x += 1else: x -= 1 x_coords.append(x) y_coords.append(y)return x_coords, y_coordsx, y = random_walk(5000)plt.plot(x, y, linewidth=0.5)plt.title("二维随机行走 (布朗运动)")plt.axis('equal')plt.show()解释:每次随机选择方向移动一步,轨迹像醉汉路线,常用于物理、金融和游戏AI中的随机探索模拟。
import randomfrom colorama import Fore, Style, init # 需要 pip install coloramainit(autoreset=True)defrandom_ascii_art(width=40, height=10): chars = ['█', '▓', '▒', '░', '●', '○', '◆', '◈'] colors = [Fore.RED, Fore.GREEN, Fore.YELLOW, Fore.BLUE, Fore.MAGENTA, Fore.CYAN]for _ in range(height): line = ''for _ in range(width): char = random.choice(chars) color = random.choice(colors) line += color + char + ' '# 每个字符后加空格避免粘连 print(line)random_ascii_art(30, 8)输出示例(终端中会五彩斑斓):

解释:随机组合字符和ANSI颜色,每次运行都生成独特的“故障艺术”风格图案。适合在终端里展示随机动态效果。
choicesample, shuffle, choices, uniform | ||
random |
random 模块不仅强大,还充满可玩性。学习阶段写代码时,可以多用它来提高趣味性。