内置数学函数
11 methods无需导入即可使用的内置数值函数。
abs(x)返回 x 的绝对值。
Parameters
| Name | Type | Description |
|---|---|---|
| x | int | float | complex | 数字。 |
Returns
int | float
Example
python
abs(-5) # 5
abs(-3.14) # 3.14
abs(3 + 4j) # 5.0round(number[, ndigits])将 number 舍入到 ndigits 精度(默认 0)。使用银行家舍入法。
Parameters
| Name | Type | Description |
|---|---|---|
| number | float | 要舍入的数字。 |
| ndigits | int | 小数位数(默认 0)。 |
Returns
int | float
Example
python
round(3.14159, 2) # 3.14
round(2.5) # 2 (banker's rounding)
round(3.5) # 4min(iterable, *[, key, default])返回可迭代对象或参数中的最小元素。
Parameters
| Name | Type | Description |
|---|---|---|
| iterable | Iterable | 元素的可迭代对象。 |
| key | Callable | None | 提取比较键的函数。 |
| default | Any | 可迭代对象为空时返回的值。 |
Returns
Any
Example
python
min([3, 1, 2]) # 1
min(3, 1, 2) # 1
min(['bb', 'a'], key=len) # 'a'max(iterable, *[, key, default])返回可迭代对象或参数中的最大元素。
Parameters
| Name | Type | Description |
|---|---|---|
| iterable | Iterable | 元素的可迭代对象。 |
| key | Callable | None | 提取比较键的函数。 |
| default | Any | 可迭代对象为空时返回的值。 |
Returns
Any
Example
python
max([3, 1, 2]) # 3
max('hello') # 'o'
max(['bb', 'aaa'], key=len) # 'aaa'sum(iterable[, start])对 iterable 的元素求和,从 start 开始(默认 0)。
Parameters
| Name | Type | Description |
|---|---|---|
| iterable | Iterable[number] | 数字的可迭代对象。 |
| start | number | 初始值。 |
Returns
number
Example
python
sum([1, 2, 3]) # 6
sum([1, 2, 3], 10) # 16
sum([[1], [2]], []) # [1, 2]pow(base, exp[, mod])返回 base**exp。如果给定 mod,则返回 base**exp % mod(高效的模幂运算)。
Parameters
| Name | Type | Description |
|---|---|---|
| base | number | 底数。 |
| exp | number | 指数。 |
| mod | int | 模数。 |
Returns
number
Example
python
pow(2, 10) # 1024
pow(2, 10, 1000) # 24 (== 1024 % 1000)divmod(a, b)以元组形式返回 (a // b, a % b)。
Parameters
| Name | Type | Description |
|---|---|---|
| a | number | 被除数。 |
| b | number | 除数。 |
Returns
tuple[number, number]
Example
python
divmod(7, 3) # (2, 1)
divmod(10, 2) # (5, 0)chr(i)返回 Unicode 码点为 i 的字符对应的字符串。
Parameters
| Name | Type | Description |
|---|---|---|
| i | int | Unicode 码点(0..0x10FFFF)。 |
Returns
str
Example
python
chr(65) # 'A'
chr(97) # 'a'
chr(8364) # '€'ord(c)返回单个字符的 Unicode 码点。
Parameters
| Name | Type | Description |
|---|---|---|
| c | str | 单个字符。 |
Returns
int
Example
python
ord('A') # 65
ord('a') # 97
ord('€') # 8364hex(x)返回整数的十六进制字符串表示,以 '0x' 为前缀。
Parameters
| Name | Type | Description |
|---|---|---|
| x | int | 要转换的整数。 |
Returns
str
Example
python
hex(255) # '0xff'
hex(16) # '0x10'
hex(-10) # '-0xa'bin(x)返回整数的二进制字符串表示,以 '0b' 为前缀。
Parameters
| Name | Type | Description |
|---|---|---|
| x | int | 要转换的整数。 |
Returns
str
Example
python
bin(10) # '0b1010'
bin(255) # '0b11111111'
bin(-5) # '-0b101'