前言
大家好,我是倔强青铜三 。欢迎关注我,微信公众号:倔强青铜三。欢迎点赞、收藏、关注,一键三连!!!
欢迎来到 苦练Python第 44 天! 今天一起征服三大标准库:math
、random
、statistics
,从高等数学到随机游戏、再到数据分析,一网打尽。
🧮 1. math
模块:数学武器库
先导入:
python
import math
✅ 常用函数
python
print(math.sqrt(16)) # 4.0
print(math.factorial(5)) # 120
print(math.pow(2, 3)) # 8.0
print(math.ceil(4.3)) # 5
print(math.floor(4.7)) # 4
✅ 数学常数
python
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
✅ 三角函数
python
print(math.sin(math.radians(30))) # 0.5
print(math.cos(math.radians(60))) # 0.5
print(math.tan(math.radians(45))) # 1.0
🎲 2. random
模块:随机即自由
导入:
python
import random
✅ 基本随机数
python
print(random.randint(1, 10)) # 1~10 随机整数
print(random.uniform(1.5, 5.5)) # 1.5~5.5 随机浮点数
✅ 随机选择
python
colors = ['red', 'blue', 'green']
print(random.choice(colors)) # 随机挑一个颜色
✅ 洗牌
python
cards = [1, 2, 3, 4, 5]
random.shuffle(cards)
print(cards)
✅ 无放回抽样
python
print(random.sample(colors, 2)) # 随机抽出两种颜色
📊 3. statistics
模块:五秒出统计
导入:
python
import statistics
✅ 一键描述统计
python
data = [2, 4, 4, 4, 5, 5, 7, 9]
print(statistics.mean(data)) # 5.0
print(statistics.median(data)) # 4.5
print(statistics.mode(data)) # 4
print(statistics.stdev(data)) # 标准差
print(statistics.variance(data)) # 方差
🛠️ 实战场景
🎮 掷骰子
python
dice_roll = random.randint(1, 6)
print("你掷出了:", dice_roll)
📈 销售数据速览
python
sales = [120, 130, 115, 140, 150]
print("平均销售额:", statistics.mean(sales))
🎲 单位圆内随机点
python
points = [(random.uniform(-1, 1), random.uniform(-1, 1)) for _ in range(5)]
print(points)
📌 小结速记
math
:高级数学与常数random
:随机数、随机抽样、洗牌statistics
:均值、中位数、众数、标准差、方差
🧪 动手挑战
- 生成 10 个 1~100 的随机整数,计算
- 均值
- 中位数
- 标准差
- 写一个函数,模拟掷两枚骰子并返回总和。
- 用
math
计算半径 1~10 随机圆的面积。
最后感谢阅读!欢迎关注我,微信公众号 :
倔强青铜三
。欢迎点赞
、收藏
、关注
,一键三连!