Python 数值
Python 中有三种数值类型:
- int
- float
- complex
为变量赋值时,将创建数值类型的变量:
x = 1 # int
y = 2.8 # float
z = 1j # complex
如需验证 Python 中任何对象的类型,请使用 type() 函数:
print(type(x))
print(type(y))
print(type(z))
Int
Int 或整数是完整的数字,正数或负数,没有小数,长度不限。
实例
Integers:
x = 1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Float
实例
浮点 :
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
实例
浮点:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
复数
实例
复数:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
类型转换
您可以使用 int(), float(), complex()方法从一种类型转换为另一种类型
实例
从一种类型转换为另一种类型:
x = 1 # int
y = 2.8 # float
z = 1j # complex
# 从 int 转换为 float:
a = float(x)
# 从浮点数转换为整数:
b = int(y)
# 从 int 转换为 complex:
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
注释: 您无法将复数转换为其他数字类型。
随机数
Python 没有 random() 函数来创建随机数,但 Python 有一个名为 random 的内置模块,可用于生成随机数:
实例
导入 random 模块,并显示 1 到 9 之间的随机数:
import random
print(random.randrange(1, 10))