
2.1 数字类型
2.1.1 基本数字类型
Python基本的数字类型有以下几种。
➢ int:有符号整数。
➢ bool:布尔值。
➢ float:浮点数。
➢ complex:复数。
简单来说,大致只需要知道,数字有正负之分,有的有小数点,有的没有小数点,这些就够了。
布尔值就是真或假,它也是整数类型,真值用True表示,对应数字1;假值用False表示,对应数字0。注意这两个单词的大小写。
浮点数就是有小数点的数,而复数基本上是平时用不到的。
2.1.2 不同进制的整数数字表示方式
我们平时使用的数字主要是十进制数,不加任何说明,Python也默认采用十进制数输出。如果使用的是八进制、十六进制、二进制数,则需要在数字前面加上对应的前缀。
➢ 以0o或0O(数字0和字母O)开头的数字代表八进制数。
➢ 以0x或0X开头的数字代表十六进制数。
➢ 以0b或0B开头的数字代表二进制数。
注意,不管输入的是何种格式,Python均默认采用十进制数输出。代码如下:


也许你会说你对数制转换不熟悉,但实际上你经常在做数制的转换,而且能够非常熟练地转换,这个转换是对时间进行的。例如,1周零1天是几天?2年零2个月共有几个月?2小时3分4秒是多少秒?你都能熟练而准确地给出答案。按周计算是七进制,按年计算是十二进制,按小时计算就是六十进制。那么如果一周有8天,1周零1天有多少天呢?一年有16个月,2年零3个月是多少个月呢?这就很明白了吧。
2.1.3 算术运算符
标准运算符有加(+)、减(-)、乘(*)、除(/)、求模(%)和幂(**)运算符。这些运算符是我们平时经常用到的,有些无须特别说明。首先需要解释的是除法,先看一个例子:

这里的除法是“真正的除法”。如果只想得到整数,不出现小数同时舍弃余数,则可以采用如下的形式:

要想得到余数,采用模运算(求余):

如果既想得到商又想得到余数,则需要借助内建函数:


幂运算(**)用于计算一个数的N次方,下面的例子是求3的4次方:

2.1.4 比较运算符
比较运算符有小于(<)、小于等于(<=)、大于(>)、大于等于(>=)、等于(==)和不等于(!=)。
判断是否相等的符号采用了双等号,如果错误地写成了一个等号,那么Python会认为是赋值操作符,而不是比较操作符。
Python还支持连续比较:

比较操作最终返回的结果为真或假,上述的两个例子等价于:

第二个连续比较的例子,语法没有任何错误,但是不同的人理解起来不一样,会有歧义,也就是代码的可读性不好。所以推荐做法是全部采用小于号或者全部采用大于号。
2.1.5 逻辑运算符
逻辑运算符有表示与的and、表示或的or和表示非的not(即常说的【与或非】操作)。
and两边表达式的结果都为True,最终结果才为True:

or两边表达式的结果只要有一方是True,最终结果就是True;两边全为False,最终结果才为False:

not将True变为False,将False变为True:

需要特别说明的是,各种运算符都有优先级高低之分。算术运算符的优先级高于比较运算符,比较运算符的优先级高于逻辑运算符。同一级别内的运算符也有优先级高低之分,如算术运算符中,乘除法的优先级比加减法高。然而,优先级高低的顺序并不一定必须记住,更好的做法是使用括号:既省去了记忆的麻烦,又提高了可读性。如下所示:

在上面的表达式中,not的优先级比or高,先计算not 10 < 20,再与10 < 30的结果做or运算。如果写成下面的样子,则可读性会更好一些:

同样的道理,下面的四则运算中,幂运算的优先级最高:

如果写成下面的样子,则可读性会更好一些:
