Python数学运算常用标准库 math,随机抽样常用 random。开方、取整、三角函数、随机整数、打乱列表、固定种子以便复现测试,都是高频操作。下面按模块分开说明。
先算几个数
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))三角与取整
三角函数的参数是弧度。角度可用 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 原地打乱,返回值是 None,不要写成 lst = random.shufflelst)。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不含右端。