整数
Python可以处理任意大小的整数,在程序中的表示方法和数学上的写法一模一样,例如:1
,100
,-8080
,0
,等等。
计算机由于使用二进制,所以,有时候用十六进制表示整数比较方便,十六进制用0x
前缀和0-9,a-f表示,例如:0xff00
,0xa5b4c3d2
,等等。
浮点数
浮点数也就是小数,之所以称为浮点数,是因为按照科学记数法表示时,一个浮点数的小数点位置是可变的,比如,1.23×109和12.3×108是完全相等的。浮点数可以用数学写法,如1.23
,3.14
,-9.01
,等等。但是对于很大或很小的浮点数,就必须用科学计数法表示,把10用e替代,1.23×109就是1.23e9
,或者12.3e8
,0.000012可以写成1.2e-5
,等等。
整数和浮点数在计算机内部存储的方式是不同的,整数运算永远是精确的,而浮点数运算则可能会有四舍五入的误差。
布尔值
布尔值和布尔代数的表示完全一致,一个布尔值只有True
、False
两种值,要么是True
,要么是False
,在Python中,可以直接用True
、False
表示布尔值(请注意大小写),也可以通过布尔运算计算出来:
>>> True
True
>>> False
False
>>> 3 > 2
True
>>> 3 > 5
False
布尔值可以用and
、or
和not
运算。and
运算是与运算,只有所有都为True
,and
运算结果才是True
:
>>> True and True
True
>>> True and False
False
>>> False and False
False
>>> 5 > 3 and 3 > 1
True
or
运算是或运算,只要其中有一个为True
,or
运算结果就是True
:
>>> True or True
True
>>> True or False
True
>>> False or False
False
>>> 5 > 3 or 1 > 3
True
not
运算是非运算,它是一个单目运算符,把True
变成False
,False
变成True
:
>>> not True
False
>>> not False
True
>>> not 1 > 2
True
布尔值经常用在条件判断中,比如:
if age >= 18:
print('adult')
else:
print('teenager')
Python3 数字(Number)