第十八章、常用内置函数
内置函数
内置函数通常由C语言编写的函数,它定义在标准库中的 __builtins__
模块中。
标准库模块的导入:
from __builtins__ import *
以上操作在 python程序启动前就已经完成,不用开发者自己导入。
查看 __builtins__
内置模块
>>> help(__builtins__)
学过的内置函数
类型
函数
基本输入输出函数
print()、input()
类的构造函数
int()、bool()、float()、complex()、str()、list()、tuple()、dict()、set()、frozenset()
容器统计函数
len()、sum()、max()、min()
布尔运算函数
any()、all()
整数生成器函数
range()
类和对象函数
id()、dir()、isinstance()、issubclass()、type()、super()
文件打开函数
open()
帮助函数
help()
本章要学的内置函数
类型
函数
数学运算函数
abs()、pow()、round()、divmod()
整数进制转换函数
bin()、oct()、hex()
字符编码函数
chr()、ord()
排序函数
sorted()
1. 数学运算相关的内置函数
数学运算相关的内置函数
函数
说明
abs(x)
返回一个数字的绝对值。 参数可以是整数、浮点数。 如果参数是一个复数,则返回它的模。
pow(base, exp, mod=None)
返回 base 的 exp 次幂;如果 mod 存在,则返回 base 的 exp 次幂对 mod 取余(比 pow(base, exp) % mod 更高效)。 两参数形式 pow(base, exp) 等价于乘方运算符: base**exp。
round(number, ndigits=None)
返回 number 舍入到小数点后 ndigits 位精度的值。 如果 ndigits 被省略或为 None,则返回最接近输入值的整数。
divmod(a, b)
接受两个(非复数)数字作为参数并返回由当对其使用整数除法时的商和余数组成的数字对。
示例
>>> abs(100)
100
>>> abs(-100)
100
>>> pow(5, 2)
25
>>> pow(5, 2, 3)
1
>>> round(3.1415926, 3)
3.142
>>> round(3.1415926, 2)
3.14
>>> round(3.1415926)
3
>>> divmod(14, 3)
(4, 2)