番外篇·下:仙界游历

第四十五章:天道算数 (Math & Random)

← 上一章 | 返回宗门地图
路人
Py
老祖,修仙不仅要打打杀杀,还要懂得 推演天机
比如计算飞剑的抛物线,预测渡劫的成功率...
只靠加减乘除似乎不够用啊?
吉多
老祖
那是因为你还未掌握 天道算数
Python 内置了 math (精准法则) 和 random (混沌法则)。
掌握它们,你便是这方天地的 主宰

1. 精准法则 (Math)

这是天地间不可动摇的真理。

import math

# 圆周率之谜
print(math.pi)  # 3.1415926...

# 开天眼 (平方根)
print(math.sqrt(81))  # 9.0

# 向上取整 (天花板)
print(math.ceil(3.1))  # 4

# 三角阵法
print(math.sin(math.pi / 2))  # 1.0

2. 混沌法则 (Random)

这是命运的轮盘,一切皆有可能。

import random

# 投掷命运骰子 (1-6)
dice = random.randint(1, 6)
print(f"骰子点数: {dice}")

# 随机抽取一名幸运弟子祭天
disciples = ['张三', '李四', '王五']
lucky_one = random.choice(disciples)

# 洗牌 (打乱列表)
cards = ['A', '2', '3', '4', '5']
random.shuffle(cards)
print(f"乱序牌组: {cards}")

3. 统计之道 (Statistics)

当样本足够多时,混沌中也会诞生秩序。

import statistics

scores = [80, 90, 100, 70, 85, 95]

# 平均修为
print(statistics.mean(scores))  # 86.66...

# 中位数 (众生相)
print(statistics.median(scores))  # 87.5

🎮 试练:混沌预测

任务:如果你想生成一个 0.0 到 1.0 之间的随机浮点数,应该用 random 模块的哪个函数?

命运之轮正在旋转...
>>>
下一章:天机封印 →