1. 使用`import`关键字导入`math`库:
import math
2. 使用`math`库中的函数和常量时,需要在函数或常量前加上`math.`前缀:
计算平方根
x = math.sqrt(25)
print(x) 输出结果为5.0
获取圆周率π的值
print(math.pi)
3. 如果你只需要导入`math`库中的特定函数或常量,可以使用`from...import`语句:
from math import sqrt, pi
直接使用导入的函数
x = sqrt(25)
print(x) 输出结果为5.0
使用导入的常量
print(pi)
4. 如果需要,可以使用`from...import *`语句将`math`库的所有内容导入到当前命名空间中,但通常不推荐这样做,因为它可能导致命名冲突:
from math import *
之后可以使用任何math库中的函数和常量,无需前缀
x = sqrt(25)
print(x) 输出结果为5.0
print(pi)