Python基础教程

008_Python数字类型共4种

Python数字类型共4种

Python的4种数字类型

Python中数字类型有4种,分别是整型int、浮点型float、复数complex和布尔bool。

使用示例如下。

a=10
b=10.5
c=10+6j
d=True
print(a,type(a))
print(b,type(b))
print(c,type(c))
print(d,type(d))

运行结果如下

C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/py001/t09.py
10 <class 'int'>
10.5 <class 'float'>
(10+6j) <class 'complex'>
True <class 'bool'>

Process finished with exit code 0

前面讲过,int是变长度类型,所以不用担心数据太大,内存溢出。而float是定长度类型,数据大小会有界限。

import sys
print(sys.float_info)

运行结果如下

C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/py001/t09.py
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)

Process finished with exit code 0

可以看到float有最大和最小范围。当然,普通使用不会超过此范围。

下面看一下超过范围,内存溢出的情况。

a=10.0**308
print(a)
a=10.0**309
print(a)

运行结果如下

C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/py001/t09.py
Traceback (most recent call last):
  File "E:/wkp01/p00/test01/py001/t09.py", line 3, in <module>
    a=10.0**309
OverflowError: (34, 'Result too large')
1e+308

Process finished with exit code 1

第一行代码不溢出,第三行代码溢出。

复数complex很少用到。布尔bool类型就是True和False两个值,主要用于条件判断,相当于1和0。

数学运算

Python数字类型主要用于数学运算。

算术运算符包括7种:加(+)、减(-)、乘(*)、除(/)、取模(%)、幂(**)、取整除(//)。

a=10
if a % 2 == 0:
    print("偶数")

比如隔行处理时经常会用到取模运算。

数值取整

数值取整有下面4种方法

  • int() 向下取整 内置函数
  • round() 四舍五入 内置函数
  • floor() 向下取整 math模块函数
  • ceil() 向上取整 math模块函数
import math
print("int 2.3",int(2.3))       # 2
print("int 2.7",int(2.7))       # 2
print("round 2.3",round(2.3))   # 2
print("round 2.7",round(2.7))   # 3
print("math.floor 2.3",math.floor(2.3)) # 2
print("math.floor 2.7",math.floor(2.7)) # 2
print("math.ceil 2.3",math.ceil(2.3))   # 3
print("math.ceil 2.7",math.ceil(2.7))   # 3

运行结果

C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/py001/t09.py
int 2.3 2
int 2.7 2
round 2.3 2
round 2.7 3
math.floor 2.3 2
math.floor 2.7 2
math.ceil 2.3 3
math.ceil 2.7 3

Process finished with exit code 0

保留小数有效位数

保留小数有效位数方法有3种:

  • round() 四舍五入 内置函数
  • format() 格式控制
  • % 格式控制
print(round(2.673,2))      # 2.67
print(round(2.677,2))      # 2.68
print(format(2.673,".2f")) # 2.67
print(format(2.677,".2f")) # 2.68
a=('%.2f'%2.673)
b=('%.2f'%2.677)
print(a)                   # 2.67
print(b)                   # 2.68

浮点数在内存中存储不准,比如0.005在内存中实际存储可能是0.00499999999999999999999999999。如果这时对其(0.004)四舍五入(0.00)时会被舍去,而得不到想要的四舍五入效果(0.01)。

print(round(2.675,2))       # 2.67
print(round(2.6751,2))      # 2.68
print(format(2.675,".2f"))  # 2.67
print(format(2.6751,".2f")) # 2.68
a=('%.2f'%2.675)
b=('%.2f'%2.6751)
print(a)                    # 2.67
print(b)                    # 2.68

2.6751=2.675+0.0001。看起为增加了一个无关紧要的0.0001,实际上改变了内存存储0.005(0.004999999)现象。

这篇文章对您有用吗?

我们要如何帮助您?