Python 数值

Python 中有三种数值类型:

  • int
  • float
  • complex

为变量赋值时,将创建数值类型的变量:

  1. x = 1 # int
  2. y = 2.8 # float
  3. z = 1j # complex

如需验证 Python 中任何对象的类型,请使用 type() 函数:

  1. print(type(x))
  2. print(type(y))
  3. print(type(z))

Int

Int 或整数是完整的数字,正数或负数,没有小数,长度不限。

实例

Integers:

  1. x = 1
  2. y = 35656222554887711
  3. z = -3255522
  4. print(type(x))
  5. print(type(y))
  6. print(type(z))

Float

浮动或”浮点数”是包含小数的正数或负数。

实例

浮点 :

  1. x = 1.10
  2. y = 1.0
  3. z = -35.59
  4. print(type(x))
  5. print(type(y))
  6. print(type(z))

浮点数也可以是带有”e”的科学数字,表示 10 的幂。

实例

浮点:

  1. x = 35e3
  2. y = 12E4
  3. z = -87.7e100
  4. print(type(x))
  5. print(type(y))
  6. print(type(z))

复数

复数用 “j” 作为虚部编写:

实例

复数:

  1. x = 3+5j
  2. y = 5j
  3. z = -5j
  4. print(type(x))
  5. print(type(y))
  6. print(type(z))

类型转换

您可以使用 int(), float(), complex()方法从一种类型转换为另一种类型

实例

从一种类型转换为另一种类型:

  1. x = 1 # int
  2. y = 2.8 # float
  3. z = 1j # complex
  4. # 从 int 转换为 float:
  5. a = float(x)
  6. # 从浮点数转换为整数:
  7. b = int(y)
  8. # 从 int 转换为 complex:
  9. c = complex(x)
  10. print(a)
  11. print(b)
  12. print(c)
  13. print(type(a))
  14. print(type(b))
  15. print(type(c))

注释: 您无法将复数转换为其他数字类型。

随机数

Python 没有 random() 函数来创建随机数,但 Python 有一个名为 random 的内置模块,可用于生成随机数:

实例

导入 random 模块,并显示 1 到 9 之间的随机数:

  1. import random
  2. print(random.randrange(1, 10))