python|数值类型
Python 提供了多种内置数值类型,主要包括 int、float、complex、bool。
类型 | 英文名称 | 示例 | 说明 |
int | 整数 (integer) | x = 10 | 任意大小整数 |
float | 浮点数 (floating point) | x = 3.14 | 带小数点的数值 |
complex | 复数 (complex number) | x = 2 + 3j | 包含实部与虚部 |
bool | 布尔值 (boolean) | x = True | True 或 False,是 int 的子类 |
一、int 整型
整数类型,支持任意精度,不会溢出。
a = 10
b = 3
print(a + b) # 13
print(a - b) # 7
print(a * b) # 30
print(a // b) # 3 整除
print(a % b) # 1 取余
print(a ** b) # 1000 幂运算
二、float 浮点型
浮点数表示带小数点的实数,使用 IEEE 754 标准。
x = 0.1 + 0.2
print(x) # 0.30000000000000004 (浮点误差)
pi = 3.1415926
print(f"{pi:.2f}") # 3.14
print(round(pi, 3)) # 3.142
三、complex 复数型
Python 内置支持复数,用 j 表示虚数部分。
z = 2 + 3j
print(z.real) # 实部:2.0
print(z.imag) # 虚部:3.0
print(z.conjugate()) # 共轭复数:2 - 3j
a = 1 + 2j
b = 3 - 4j
print(a + b) # (4 - 2j)
print(a * b) # (11 + 2j)
四、bool 布尔型
布尔值 True/False,本质上是 int 的子类。
print(isinstance(True, int)) # True
print(True == 1) # True
print(False == 0) # True
x = True
y = False
print(x and y) # False
print(x or y) # True
print(not x) # False
五、类型转换与混合运算
Python 支持隐式与显式类型转换。
x = 1
y = 2.5
print(x + y) # 3.5 (int + float -> float)
print(int(3.9)) # 3
print(float(10)) # 10.0
print(complex(5)) # (5+0j)
print(bool(0)) # False
六、常用数学函数与模块
Python 内置 math 和 cmath 模块,用于数学与复数计算。
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793
print(math.ceil(3.2)) # 4
print(math.floor(3.8)) # 3
import cmath
print(cmath.sqrt(-1)) # 1j
七、总结对比表
类型 | 示例 | 说明 | 常见操作 |
int | 10 | 整数,无限精度 | + - * // % ** |
float | 3.14 | 浮点数,有精度误差 | + - * / ** |
complex | 2+3j | 复数,实部虚部可运算 | + - * / |
bool | True | 布尔值,0/1 表示 | and or not |