🐸

魔法卷轴

Python 基础python-architect-12-the-scroll
奖励: 80 XP
|

Hoppy 在堡垒深处发现了一个巨大的图书馆。架子上摆满了“卷轴”(模块 Modules)。

如果古代的巫师已经把咒语写得尽善尽美了,我们通过什么还要从头开始写呢?

import 咒语

要使用图书馆里的卷轴,你必须先 import(引入)它。然后你就可以通过 卷轴名.咒语名 来使用它的力量。

import math

print(math.pi)    # 3.14159...
print(math.sqrt(16)) # 平方根: 4.0
1
引入 math

在代码顶部,输入 import math

2
使用 Pi 的力量

圆面积的公式是 $\pi r^2$。 修改 area = 0,将其替换为 math.pi * radius * radius

Python 图书馆里有成千上万个卷轴(模块)。math(数学), random(随机), time(时间), json... 力量无穷无尽!

参考答案
点击展开
参考答案:
import math # 第一步:引入卷轴

radius = 5
# 第二步:使用公式 pi * r^2
area = math.pi * radius * radius

print("Area of the circle: " + str(area))
高级技巧
想更进一步?点击展开

F. 标准库

  • Python 号称“电池内置”(Batteries Included)。这意味着你安装 Python 时就免费获得了大量强大的模块(卷轴)。
  • 你不需要下载 math,它已经在那里等你使用了。
Loading...
终端输出
Terminal
Ready to run...