Skip to content

Python Math API

Python 内置数值函数 —— abs、round、min、max、sum、pow、divmod 及转换函数。

1 class · 11 methods

内置数学函数

11 methods

无需导入即可使用的内置数值函数。

abs(x)

返回 x 的绝对值。

Parameters

NameTypeDescription
xint | float | complex数字。

Returns

int | float

Example

python
abs(-5)      # 5
abs(-3.14)   # 3.14
abs(3 + 4j)  # 5.0
round(number[, ndigits])

将 number 舍入到 ndigits 精度(默认 0)。使用银行家舍入法。

Parameters

NameTypeDescription
numberfloat要舍入的数字。
ndigitsint小数位数(默认 0)。

Returns

int | float

Example

python
round(3.14159, 2)  # 3.14
round(2.5)         # 2 (banker's rounding)
round(3.5)         # 4
min(iterable, *[, key, default])

返回可迭代对象或参数中的最小元素。

Parameters

NameTypeDescription
iterableIterable元素的可迭代对象。
keyCallable | None提取比较键的函数。
defaultAny可迭代对象为空时返回的值。

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

NameTypeDescription
iterableIterable元素的可迭代对象。
keyCallable | None提取比较键的函数。
defaultAny可迭代对象为空时返回的值。

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

NameTypeDescription
iterableIterable[number]数字的可迭代对象。
startnumber初始值。

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

NameTypeDescription
basenumber底数。
expnumber指数。
modint模数。

Returns

number

Example

python
pow(2, 10)        # 1024
pow(2, 10, 1000)  # 24  (== 1024 % 1000)
divmod(a, b)

以元组形式返回 (a // b, a % b)。

Parameters

NameTypeDescription
anumber被除数。
bnumber除数。

Returns

tuple[number, number]

Example

python
divmod(7, 3)   # (2, 1)
divmod(10, 2)  # (5, 0)
chr(i)

返回 Unicode 码点为 i 的字符对应的字符串。

Parameters

NameTypeDescription
iintUnicode 码点(0..0x10FFFF)。

Returns

str

Example

python
chr(65)   # 'A'
chr(97)   # 'a'
chr(8364) # '€'
ord(c)

返回单个字符的 Unicode 码点。

Parameters

NameTypeDescription
cstr单个字符。

Returns

int

Example

python
ord('A')  # 65
ord('a')  # 97
ord('€')  # 8364
hex(x)

返回整数的十六进制字符串表示,以 '0x' 为前缀。

Parameters

NameTypeDescription
xint要转换的整数。

Returns

str

Example

python
hex(255)   # '0xff'
hex(16)    # '0x10'
hex(-10)   # '-0xa'
bin(x)

返回整数的二进制字符串表示,以 '0b' 为前缀。

Parameters

NameTypeDescription
xint要转换的整数。

Returns

str

Example

python
bin(10)   # '0b1010'
bin(255)  # '0b11111111'
bin(-5)   # '-0b101'