python中有哪些内置函数可用于编写数值表达式?
在 Python 中,用于编写数值表达式的内置函数很多,它们可以帮助你处理数学运算、类型转换、数值判断等。以下是常用的 内置函数(不需要导入模块)按类别归类说明:
一、基础数值处理函数
函数 | 作用 | 示例 |
abs(x) | 取绝对值 | abs(-3.5) → 3.5 |
round(x, n=0) | 四舍五入到 n 位小数 | round(3.14159, 2) → 3.14 |
pow(x, y) | 幂运算(等价于 x**y) | pow(2, 3) → 8 |
divmod(a, b) | 返回 (a // b, a % b) 的元组 | divmod(9, 4) → (2, 1) |
max(iterable, *args) | 返回最大值 | max(3, 5, 1) → 5 |
min(iterable, *args) | 返回最小值 | min([3, 5, 1]) → 1 |
sum(iterable, start=0) | 对 iterable 求和 | sum([1, 2, 3]) → 6 |
二、类型转换相关(用于构造数值表达式)
函数 | 作用 | 示例 |
int(x) | 转换为整数 | int(3.9) → 3 |
float(x) | 转换为浮点数 | float("3.14") → 3.14 |
complex(real, imag=0) | 构造复数 | complex(2, 3) → (2+3j) |
bool(x) | 转换为布尔值 | bool(0) → False |
三、辅助函数(常用于表达式的构建和控制)
函数 | 作用 | 示例 |
range(start, stop[, step]) | 生成整数序列 | range(1, 5) → 1,2,3,4 |
enumerate(iterable, start=0) | 返回索引和值 | enumerate([10, 20]) → (0, 10), (1, 20) |
map(func, iterable) | 对序列中每个元素执行函数 | map(abs, [-1, -2]) → 1, 2 |
filter(func, iterable) | 过滤满足条件的元素 | filter(lambda x: x > 0, [-1, 2]) → 2 |
四、可用于数值判断(辅助表达式逻辑)
函数 | 作用 | 示例 |
isinstance(x, type) | 判断类型 | isinstance(3.14, float) → True |
all(iterable) | 所有元素为真返回 True | all([1, 2, 3]) → True |
any(iterable) | 任一元素为真返回 True | any([0, 0, 1]) → True |
小拓展:标准库 math 模块(需要导入)
虽然不是内置函数,但在数值表达式中经常使用:
import math
math.sqrt(9) → 3.0
math.log(8, 2) → 3.0
math.sin(math.pi / 2) → 1.0