编程学习 /Python /进阶提高 /math 与 random:数字工具箱
🐍 Python 进阶提高

math 与 random:数字工具箱

常用数学函数与随机数生成,附一个抽签小例子。

📅 2026-11-23 👁 1 次阅读 🔗 根据 W3School Python 教程整理优化:https://www.w3school.com.cn/python/python_math.asp
math 与 random:数字工具箱示意图

math 模块常用函数

import math

print(math.sqrt(16))     # 4.0
print(math.ceil(2.1))    # 3 向上取整
print(math.floor(2.9))   # 2 向下取整
print(round(2.675, 2))   # 2.67,注意浮点精度
print(math.pi)           # 3.14159...

random 模块

import random

print(random.randint(1, 10))       # 含两端的整数
print(random.choice(['苹果', '梨']))
items = [1, 2, 3, 4]
random.shuffle(items)
print(items)

小例子:随机抽签

names = ['小明', '小红', '小刚']
winner = random.sample(names, 1)[0]
print(f'本次中奖者是:{winner}')
本站提示:涉及验证码、令牌等安全场景时不要用 random,改用 secrets 模块。

本文根据 W3School Python 教程 的知识点重新整理、补充示例编写,非原文转载。