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

前言

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

欢迎来到 苦练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:均值、中位数、众数、标准差、方差

🧪 动手挑战

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

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

相关推荐
汤姆宝库2 小时前
世界模型深拆:视频生成、潜在模拟与物理直觉
人工智能
weixin_468466855 小时前
从“看懂”到“做到”:视觉-语言-动作模型如何让机器人真正执行指令
人工智能·ai·机器人·大语言模型·前沿科技
朋友圈自动点赞工具5 小时前
科学AI插件化:从蛋白质结构到古籍修复
人工智能
龙粤GEO6 小时前
实体Entity在GEO中代表什么含义
人工智能
夕除6 小时前
Redis 过期策略
redis·笔记·面试
前端精髓6 小时前
结构化输出with_structured_output(抽卡)
python·langchain
尹人入圣7 小时前
目前热门的IP驱动产业新场景新工具
网络·python·网络协议·tcp/ip
剑雨巍巍7 小时前
AI Agent面试之基础概念
人工智能
微帧Visionular7 小时前
AI视频单帧清晰,播放时却闪烁,原因是什么?
人工智能·深度学习·音视频
武子康7 小时前
MultiNet6 空闲崩溃:`EXCVADDR=0x8` 后又出现 `CORRUPT HEAP`
人工智能·后端·agent