栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python 入门系列 —— 7. 数字类型介绍

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python 入门系列 —— 7. 数字类型介绍

数字类型

在 Python 中有三种数字类型。

  • int

  • float

  • complex

到底哪一个变量是哪一种数字类型呢?取决于你是将什么值赋给变量的。


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

要想确认这个变量是否为此类型,用 type() 函数即可。


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

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


---- output ----

PS E:dreammarkdownpython> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py


int

int 或者 integer 是一个无限大的没有小数点的整数,可正可负。


x = 1
y = 35656222554887711
z = -3255522

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

Float

Float 表示一个带有小数点的,可正可负的数字。


x = 1.10
y = 1.0
z = -35.59

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

Float 也支持科学计数法,用一个 e 来表示 10 的幂。


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

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

复数

复数是用 j 来表示虚数部分


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

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

类型转换

可以使用 int(),float(), complex() 将一个类型转换为另外一个类型。


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

#convert from int to float:
a = float(x)

#convert from float to int:
b = int(y)

#convert from int to complex:
c = complex(x)

print(a)
print(b)
print(c)

print(type(a))
print(type(b))
print(type(c))

随机数

Python 中并没有一个类似 random() 函数来生成随机数,但是 python 有一个 random 模块可用来生成随机数,接下来导入 random 模块,使用 random 来显示 1-9 之间的随机数。


import random

print(random.randrange(1, 10))


--- output ---


PS E:dreammarkdownpython> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
8
PS E:dreammarkdownpython> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
6
PS E:dreammarkdownpython> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
3

更多高质量干货:参见我的 GitHub: github.com/ctripxchuang/python

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号