在 Python 中,数学函数与常数常用标准库 math,随机整数、浮点数抽样及打乱序列常用 random。开方、取整、三角函数、随机掷骰、无放回抽样及固定随机种子以便测试复现,均属常见需求。内置 round 对恰为 .5 的值采用银行家舍入,与日常四舍五入并不完全一致。本节按模块归纳常用 API。

math 基本示例

import math

print(math.sqrt(16))
print(math.pi)
print(math.e)
print(math.floor(3.7))
print(math.ceil(3.2))

math 常用函数

import math

print(math.pow(2, 10))
print(math.fabs(-3.5))
print(math.factorial(5))
print(math.gcd(12, 8))
print(math.fmod(7, 3))
print(math.log(100, 10))
print(math.exp(1))

三角函数与 round

三角函数参数为弧度,角度可用 math.radians 转换。内置 round 在恰为 .5 时向最近偶数靠拢:

import math

print(math.sin(math.pi / 2))
print(math.cos(0))
print(math.radians(180))
print(round(3.567, 2))
print(round(3.5))

若业务要求严格的逐位四舍五入,应使用 decimal 模块,而非仅依赖内置 round。

random 常用函数

import random

print(random.randint(1, 6))
print(random.random())
print(random.uniform(1, 10))
print(random.choice(["石头", "剪刀", "布"]))
print(random.randrange(0, 10, 2))

randint(a, b) 为闭区间,两端均可取到。randrange 与 range 类似,右端点不包含。

shuffle 与 sample

shuffle 原地打乱列表,返回值为 None,勿写成 lst = random.shuffle(lst)。sample 进行无放回抽样:

import random

cards = ["A", "2", "3", "4"]
random.shuffle(cards)
print(cards)

nums = list(range(1, 100))
print(random.sample(nums, 3))

固定随机种子

相同种子下后续随机序列可复现,便于测试:

import random

random.seed(42)
print(random.randint(1, 100))
print(random.randint(1, 100))

猜数字示例

import random

target = random.randint(1, 100)
for attempt in range(1, 8):
    guess = int(input(f"第{attempt}次猜(1-100): "))
    if guess == target:
        print("猜对了!")
        break
    print("大了" if guess > target else "小了")
else:
    print("次数用完,答案是", target)

for 的 else 在循环未被 break 打断时执行,此处用于提示次数用尽。

注意事项

  • random.shuffle 原地修改列表,返回 None。
  • round 对 .5 的处理为银行家舍入;精确小数场景宜考虑 decimal。
  • randint 含两端,randrange 不含右端点。

本节说明了 Python 中 math 与 random 的常见用法。下一节介绍闭包:内层函数捕获外层变量及与装饰器的关系。