Python 数字
本章节讲述 Python 数字类型的用法。
Python 数字
Python 中有三种数字类型:
- int
- float
- complex
为变量赋值时,将创建数值类型的变量:
x = 10 # inty = 6.3 # floatz = 2j # complex
如需验证 Python 中任何对象的类型,请使用 type() 函数:
x = 10y = 6.3z = 2jprint(type(x))print(type(y))print(type(z))
Int
Int 或整数是完整的数字,正数或负数,没有小数,长度不限。
整数:
x = 10y = 37216654545182186317z = -465167846print(type(x))print(type(y))print(type(z))
Float
浮动或 "浮点数" 是包含小数的正数或负数。
浮点:
x = 3.50y = 2.0z = -63.78print(type(x))print(type(y))print(type(z))
浮点数也可以是带有 "e" 的科学数字,表示 10 的幂。
浮点:
x = 27e4y = 15E2z = -49.8e100print(type(x))print(type(y))print(type(z))
复数
复数用 "j" 作为虚部编写:
复数:
x = 2+3jy = 7jz = -7jprint(type(x))print(type(y))print(type(z))
类型转换
您可以使用 int()、float() 和 complex() 方法从一种类型转换为另一种类型:
从一种类型转换为另一种类型:
#convert from int to float:x = float(10)#convert from float to int:y = int(6.3)#convert from int to complex:z = complex(x)print(x)print(y)print(z)
注释:您无法将复数转换为其他数字类型。
随机数
Python 没有 random() 函数来创建随机数,但 Python 有一个名为 random 的内置模块,可用于生成随机数:
导入 random 模块,并显示 1 到 9 之间的随机数:
import randomprint(random.randrange(1,10))
在 Random 模块参考手册 中,您可以学习到 Random 模块的更多知识。