Python 官方文档:入门教程 => 点击学习
目录python 数字类型IntFloat复数类型转换随机数Python 数字类型 Python 中有三种数字类型: intfloatcomplex 为变量赋值时,将创建数值类型的变
Python 中有三种数字类型:
为变量赋值时,将创建数值类型的变量:
实例
x = 10 # int
y = 6.3 # float
z = 2j # complex
如需验证 Python 中任何对象的类型,请使用 type() 函数:
实例
print(type(x))
print(type(y))
print(type(z))
运行实例
Int 或整数是完整的数字,正数或负数,没有小数,长度不限。
实例
整数:
x = 10
y = 37216654545182186317
z = -465167846
print(type(x))
print(type(y))
print(type(z))
运行实例
浮动或“浮点数”是包含小数的正数或负数。
实例
浮点:
x = 3.50
y = 2.0
z = -63.78
print(type(x))
print(type(y))
print(type(z))
运行实例
浮点数也可以是带有“e”的科学数字,表示 10 的幂。
实例
浮点:
x = 27e4
y = 15E2
z = -49.8e100
print(type(x))
print(type(y))
print(type(z))
运行实例
复数用 “j” 作为虚部编写:
实例
复数:
x = 2+3j
y = 7j
z = -7j
print(type(x))
print(type(y))
print(type(z))
运行实例
您可以使用 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 没有 random() 函数来创建随机数,但 Python 有一个名为 random 的内置模块,可用于生成随机数:
实例
导入 random 模块,并显示 1 到 9 之间的随机数:
import randomprint(random.randrange(1,10))
运行实例
到此这篇关于Python入门教程(七)Python数字类型的文章就介绍到这了,更多相关Python数字类型内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Python入门教程(七)Python数字类型
本文链接: https://www.lsjlt.com/news/208418.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0