Python支持三种主要的数值类型:
int
(整数)float
(浮点数)complex
(复数)
创建数值类型变量
当你给变量赋予数值时,Python会自动为其分配对应的数据类型:
x = 1 # 整数
y = 2.5 # 浮点数
z = 3j # 复数
print(type(x))
print(type(y))
print(type(z))
整数(int)
整数是正数或负数,不带小数点,长度不受限制:
x = 5
y = 12345678901234567890
z = -256
print(type(x))
print(type(y))
print(type(z))
浮点数(float)
浮点数是带小数点的数,或者使用科学计数法表示:
x = 1.5
y = -3.6
z = 35e3 # 表示35000.0
print(type(x))
print(type(y))
print(type(z))
复数(complex)
复数以字符j
代表虚部:
x = 3+5j
y = 5j
z = -3j
print(type(x))
print(type(y))
print(type(z))
数值类型转换
你可以使用int()
、float()
、complex()
等函数进行类型转换:
x = 1 # int
y = 2.8 # float
z = 1j # complex
a = float(x) # 整数转浮点数
b = int(y) # 浮点转整数
c = complex(x) # 整数转复数
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
生成随机数
Python没有内置的随机数函数,但你可以导入random
模块来实现随机数:
import random
print(random.randrange(1, 10)) # 随机输出1到9之间的一个整数
后续章节我们还会深入了解更多关于随机数的用法。