苦练Python第44天:math、random、statistics三剑客,带你秒杀数学计算与数据分析

前言

大家好,我是倔强青铜三 。欢迎关注我,微信公众号:倔强青铜三。欢迎点赞、收藏、关注,一键三连!!!

欢迎来到 苦练Python第 44 天! 今天一起征服三大标准库:mathrandomstatistics,从高等数学到随机游戏、再到数据分析,一网打尽。


🧮 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:均值、中位数、众数、标准差、方差

🧪 动手挑战

  1. 生成 10 个 1~100 的随机整数,计算
    • 均值
    • 中位数
    • 标准差
  2. 写一个函数,模拟掷两枚骰子并返回总和。
  3. math 计算半径 1~10 随机圆的面积。

最后感谢阅读!欢迎关注我,微信公众号倔强青铜三。欢迎 点赞收藏关注,一键三连!

相关推荐
CNRio17 分钟前
人工智能基础架构与算力之3 Transformer 架构深度解析:从注意力机制到算力适配演进
人工智能·深度学习·transformer
qy-ll22 分钟前
深度学习——CNN入门
人工智能·深度学习·cnn
u***32431 小时前
使用python进行PostgreSQL 数据库连接
数据库·python·postgresql
青瓷程序设计4 小时前
动物识别系统【最新版】Python+TensorFlow+Vue3+Django+人工智能+深度学习+卷积神经网络算法
人工智能·python·深度学习
tobebetter95274 小时前
How to manage python versions on windows
开发语言·windows·python
F_D_Z4 小时前
数据集相关类代码回顾理解 | sns.distplot\%matplotlib inline\sns.scatterplot
python·深度学习·matplotlib
daidaidaiyu5 小时前
一文入门 LangGraph 开发
python·ai
金智维科技官方5 小时前
RPA财务机器人为企业高质量发展注入动能
人工智能·机器人·rpa·财务
沫儿笙5 小时前
安川机器人tag焊接怎么节省保护气
人工智能·物联网·机器人
2501_941147425 小时前
人工智能赋能智慧教育互联网应用:智能学习与教育管理优化实践探索》
人工智能