于 2020 年 1 月 7 日更新
Python 具有许多内置函数。
| 方法 | 描述 |
|---|---|
round(number[, ndigits]) |
四舍五入数字,也可以在第二个参数中指定精度 |
pow(a, b) |
将a提升到b的幂 |
abs(x) |
返回x的绝对值 |
max(x1, x2, ..., xn) |
返回提供的参数中的最大值 |
min(x1, x2, ..., xn) |
返回提供的参数中的最小值 |
下面提到的函数位于math模块中,因此您需要使用以下行首先导入math模块。
import math
| 方法 | 描述 |
|---|---|
ceil(x) |
此函数将数字四舍五入并返回其最接近的整数 |
floor(x) |
此函数将向下取整并返回其最接近的整数 |
sqrt(x) |
返回数字的平方根 |
sin(x) |
返回x的正弦,其中x以弧度表示 |
cos(x) |
返回x的余弦值,其中x为弧度 |
tan(x) |
返回x的切线,其中x为弧度 |
让我们举一些例子来更好地理解
>>> abs(-22) # Returns the absolute value22>>>>>> max(9, 3, 12, 81) # Returns the maximum number81>>>>>> min(78, 99, 12, 32) # Returns the minimum number12>>>>>> pow(8, 2) # can also be written as 8 ** 264>>>>>> pow(4.1, 3.2) # can also be written as 4.1 ** 3.291.39203368671122>>>>>> round(5.32) # Rounds to its nearest integer5>>>>>> round(3.1456875712, 3) # Return number with 3 digits after decimal point3.146
>>> import math>>> math.ceil(3.4123)4>>> math.floor(24.99231)24
在下一篇文章中,我们将学习如何在 python 中生成随机数。
