
3.2 数字类型的操作
在3.1节中了解了数字类型包括整数类型、整数的按位运算、浮点数、复数类型和布尔类型。那么在这一节中将学习数字类型的基本操作方法。
3.2.1 内置的数值操作符

在Python中,内置的操作运算符主要分为四种,分别是算术运算符、赋值运算符、逻辑运算符和关系运算符。其实例分别如下。
1. 算术运算符
算术运算符如表3-3所示。
表3-3 算术运算符

具体使用及输出如下。
【例3-8】算术运算。

2. 赋值运算符
赋值运算符如表3-4所示。
表3-4 赋值运算符

具体使用及输出如下。
【例3-9】赋值运算。

注意:除法运算结果为浮点数,和被除数与除数的类型无关。
3. 逻辑运算符
逻辑运算符如表3-5所示。
表3-5 逻辑运算符

逻辑运算主要与布尔值的判断和0、1操作有关。
【例3-10】逻辑运算。

4. 比较运算符
比较运算符如表3-6所示。
表3-6 比较运算符

【例3-11】比较运算。

3.2.2 内置的数值运算函数

内置的数值运算函数如表3-7所示。
表3-7 内置的数值运算函数

部分函数操作及其具体用法示例如下。
【例3-12】函数运算。

常见的函数操作中,部分函数的用法需要特殊记忆。下面列举的函数其用法虽然不广泛,但是对于理解Python的数据类型和存储有着较为直观的意义。
(1)函数round()与精度误差。
函数round()的作用为将浮点数A进行四舍五入,并指定小数的位数。关于舍入需要知道Python中浮点数的特征。
浮点数本身就是非精确数据。大多数十进制小数并不能完全用二进制小数来表示。因此,输入的十进制浮点数一般只能用二进制浮点数来进行近似。
例如在十进制中,对于分数1/3,将其写成小数时只能无限近似写成1.333…,同理,在面对十进制浮点小数例如0.1时,无法将其完美地换算为二进制数据,只能无限近似。Python中存在一个近似策略,用户面对的屏幕输出的十进制数值仅是被输出的一个近似值,其真实的值以二进制数值存储在机器上。上述情况告诉我们,Python以舍入形式进行数据的近似管理。
round()函数在使用上实际上也很简单。
【例3-13】round()函数。

这和人们认知中的小数近似结果一致,即四舍五入,但是有时候考虑到前面提到的存储情况时就会出现另一种状况。
【例3-14】round()函数精度。

可以清楚地看到,这似乎违背了四舍五入的基本法则,实际上这是由于计算机只能采用近似储存浮点数,导致精度误差所致。官方文档存在下列说明:

可以得知数据在近似转换为0、1储存时被进行了截断处理,因此导致了精度误差,为此round()近似函数实际上只能进行对精度要求不大的近似求值。关于精确计算,Python提供了其他选择,例如后续将要学到的math模块中的ceiling方法和将要介绍的decimal模块。
(2)pow()函数的使用。
pow(x,y[,z])函数看似等价于(x**y)%z。
【例3-15】pow()函数。

但是实际上,它们并不完全等价。
【例3-16】特殊pow()函数。

可知,Python不允许第三个操作数为浮点数,这与x**y%z存在差异,可知在使用上并不完全等价。
3.2.3 内置的数字类型转换函数

内置的数字类型转换函数如表3-8所示。
表3-8 内置的数字类型转换函数

函数使用举例如下。
【例3-17】ascii()函数。
ascii()函数类似Python 2.X中的repr()函数,结果为返回这个指定可打印对象的字符串表示,如果此对象为非ascii字符就以转义字符型输出(\x,\u等),例如中文字符串,具体实例如下。

其中,函数int(x[,base])和函数float(x[,base])内的第二个参数的含义通过以下实例来解释。
【例3-18】int()函数。

通过实例可以知道,参数base的作用是指定第一个参数的进制类型。此时的x参数不可为数字,只能为字符串、数组或者将要学到的数组列表类型。
base默认为十进制,当指定为8时是八进制,为16时是十六进制等,但注意当其为0的时候,依旧表示十进制。
对于函数complex(real,[imag]),其实例如下。
【例3-19】complex()函数。

可知参数real和imag也可以为计算式,如果第一个参数是一个字符串,它将被解释为一个复数,并且必须在没有第二个参数的情况下调用该函数。第二个参数不可以为字符串。每个参数可以是任何数字类型(包括复数)。如果省略imag,则默认为零,构造函数用作int和float之类的数字转换。如果省略两个参数,则返回0j。