验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

Python数字类型实例代码分析

阅读:511 来源:乙速云 作者:代码code

Python数字类型实例代码分析

Python 数字类型

Python 中有三种数字类型:

  • int

  • float

  • complex

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

实例

x = 10   # int
y = 6.3  # float
z = 2j   # complex

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

实例

print(type(x))
print(type(y))
print(type(z))

运行实例

Python数字类型实例代码分析

Int

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

实例

整数:

x = 10
y = 37216654545182186317
z = -465167846

print(type(x))
print(type(y))
print(type(z))

运行实例

Python数字类型实例代码分析

Float

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

实例

浮点:

x = 3.50
y = 2.0
z = -63.78

print(type(x))
print(type(y))
print(type(z))

运行实例

Python数字类型实例代码分析

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

实例

浮点:

x = 27e4
y = 15E2
z = -49.8e100

print(type(x))
print(type(y))
print(type(z))

运行实例

Python数字类型实例代码分析

复数

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

实例

复数:

x = 2+3j
y = 7j
z = -7j

print(type(x))
print(type(y))
print(type(z))

运行实例

Python数字类型实例代码分析

类型转换

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

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

x = 10 # int
y = 6.3 # 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数字类型实例代码分析

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

随机数

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

实例

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

import randomprint(random.randrange(1,10))

运行实例

Python数字类型实例代码分析

分享到:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
相关文章
{{ v.title }}
{{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
你可能感兴趣
推荐阅读 更多>