python--Python的数据类型

前言
本次主要闲聊一下python的一些数值类型,整型(int),浮点型(float),布尔类型(bool),还有e记法(科学计数法),也是属于浮点型。

数值类型介绍
整型
整型就是我们平时所说的整数。python3的整型已经和长整型进行了无缝结合,长度不受限制,python3很容易实现大数运算。
python2的长整型后面要加上L
浮点型
浮点型也就是平常我们所说的小数,例如我们的圆周率3.14,python区分整型与浮点型的唯一方式就是看有没有小数点
e记法
e记法就是我们平时所说的科学计数法,用来表示特别大或者特别小的数,例如:
>>> 0.00000078
7.8e-07
这个e,就是e记法的意思
地球到太阳的距离是1.5亿公里,转换成米,就是:150000000000
写成e记法就是:
>>> 1.5e11
150000000000.0
大家可以看出来e=10,后面跟的数字就是几次方的意思,例如说15000,就可以表示成:
>>> 1.5 * (10**4)
15000.0
>>> 1.5e4
15000.0
1
2
3
4
5
6
7
8
9
10
11
12
布尔类型
特殊的整型。True相当于整数1,False相当于整数0,例如:
>>> True + True
2
>>> True + False
1
>>> 0 + True
1
>>> True * False
0
>>> True / False
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
True / False
ZeroDivisionError: division by zero
>>>
错误原因:除数不能为0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
数值类型转换
整数(int)
整数:int()
>>> a= '520'
>>> b = int(a)
>>> b
520
>>> a = '小甲鱼'
>>> c = int(a)
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
c = int(a)
ValueError: invalid literal for int() with base 10: '小甲鱼'
错误原因是:字符编码不符合
>>> a = 5.99
>>> c = int(a)
>>> c
5
浮点数转换成整数,python会采取把小数点后面的数字截断处理,因为这样效率高
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
浮点数:float()
浮点数:float()
>>> a = 520
>>> b = float(a)
>>> b
520.0
>>> a = '520'
>>> b = float(a)
>>> b
520.0
1
2
3
4
5
6
7
8
9
字符串:str()
字符串:str()
将一个数,或任何其他类型转换成字符串,例如:
>>> a = 5.99
>>> b = str(a)
>>> b
'5.99'

>>> a = True
>>> b = str(a)
>>> b
'True'

>>> a = True + True
>>> b = str(a)
>>> b
'2'

>>> c = str(5e19)
>>> c
'5e+19'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
获取类型信息
type()函数
python提供了type()函数,来得到数据的类型。
>>> type(a)
<class 'str'>
>>>
>>> a = 5.2
>>> type(a)
<class 'float'>
>>>
>>> type(True)
<class 'bool'>
>>>
>>> type(5e19)
<class 'float'>
>>>
>>> type(1)
<class 'int'>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
isinstance()函数
python更推荐使用isinstance()函数,来得到数据类型,例如:
>>> a = '小甲鱼'
>>>
>>> isinstance(a,str)
True
>>> isinstance(a,int)
False
>>> isinstance(1,bool)
False
意思就是说,这两者类型一致,就返回True,不一致返回False
1
2
3
4
5
6
7
8
9
10
练练手
判断给定年份是否为闰年。

闰年是这样定义的:
普通年(不能被100整除的年份)能被4整除的为闰年。(如2004年就是闰年,1999年不是闰年);
世纪年(能被100整除的年份)能被400整除的是闰年。(如2000年是闰年,1900年不是闰年);

第一种写法:
temp = input('请输入一个年份:')
while not temp.isdigit():
temp = input("抱歉,您的输入有误,请输入一个整数:")

year = int(temp)
if year/400 == int(year/400):
print(temp + ' 是闰年!')
else:
if (year/4 == int(year/4)) and (year/100 != int(year/100)):
print(temp + ' 是闰年!')
else:
print(temp + ' 不是闰年!')


第二种写法:
temp = input("请输入一个年份:")
while True:
if temp.isdigit():
year = int(temp)
if (year/400) == int(year/400):
print(year,"为闰年")
else:
if ((year/4) == int(year/4)) and ((year/100) != int(year/100)):
print(year,"为闰年")
else:
print(year,"不为闰年")
break
else:
temp=input("您输入的有误,请重新输入:")

猜你喜欢

转载自www.cnblogs.com/muliti-hu/p/10921905.html