Python 数字类型

Python 内置了三种不同的数字类型: 整数(int), 浮点数(float`) 和 复数(complex)。

Python 内置了三种不同的数字类型: 整数(int), 浮点数(float) 和 复数(complex)。

x = 1    # int
y = 2.8  # float
z = 1j   # complex

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

print(type(x) # 输出 <class 'int'>
print(type(y) # 输出 <class 'float'>
print(type(z) # 输出 <class 'complex'>

整数

int 是一个整数,正负,不带小数,长度不限。

整数:

x = 1
y = 35656222554887711
z = -3255522

print(type(x)) # 输出 <class 'int'>
print(type(y)) # 输出 <class 'int'>
print(type(z)) # 输出 <class 'int'>

浮点数

float 包含一位或多位小数的正数或负数。

浮点数:

x = 1.10
y = 1.0
z = -35.59

print(type(x)) # 输出 <class 'float'>
print(type(y)) # 输出 <class 'float'>
print(type(z)) # 输出 <class 'float'>

浮点数也可以使用科学计数法表示。

科学计数法的浮点数:

x = 35e3
y = 12E4
z = -87.7e100

print(type(x)) # 输出 <class 'float'>
print(type(y)) # 输出 <class 'float'>
print(type(z)) # 输出 <class 'float'>

复数

complex 复数包含实部和虚部,分别以一个浮点数表示,带有 jJ 的部分为虚部。

复数:

x = 3+5j
y = 5j
z = -5j

print(type(x)) # 输出 <class 'complex'>
print(type(y)) # 输出 <class 'complex'>
print(type(z)) # 输出 <class 'complex'>

类型转换

你可以使用 int()float()complex() 方法将数据从一种类型转变成为另一种类型。

数据类型转换示例:

x = 1    # int
y = 2.8  # float
z = 1j   # complex

# int 转为 float:
a = float(x)

# float 转为 int:
b = int(y)

# int 转为 complex:
c = complex(x)

print(a) # 输出 1.0
print(b) # 输出 2
print(c) # 输出 (1+0j)

print(type(a)) # 输出 <class 'float'>
print(type(b)) # 输出 <class 'int'>
print(type(c)) # 输出 <class 'complex'>

!! 注意: 不能将复数转换为其他数字类型。

随机数

Python 没有内置生成随机数的函数,但是 Python 有一个内置模块 random 可以用来生成随机数。

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

import random

print(random.randrange(1, 10))