
5.3 运算符
运算符包括算术运算符、赋值运算符、比较运算符、逻辑运算符、按位运算符、成员运算符和身份运算符。
5.3.1 算术运算符

算术运算符包括加、减、乘、除、取余、取整、幂运算。Python常见的算术运算符见表5-3。
表5-3 算术运算符

【例5-18】算术运算符及表达式举例。

程序运行结果如图5-18所示。

图5-18 算术运算符举例结果
5.3.2 赋值运算符

赋值运算符除了一般的赋值运算符(=)外,还包括+=、-=、*=、/=等。Python常见的赋值运算符见表5-4。
表5-4 赋值运算符

【例5-19】赋值运算符及表达式举例。

程序运行结果如图5-19所示。

图5-19 赋值运算符举例结果
5.3.3 比较运算符

比较运算符有==、!=、>、<、>=、<=。比较运算符可以对两个数据进行比较。Python常见的比较运算符见表5-5(其中,a = 2,b = 3)。
表5-5 比较运算符

【例5-20】比较运算符及表达式举例。

程序运行结果如图5-20所示。

图5-20 比较运算符举例结果
5.3.4 逻辑运算符

逻辑运算符有and、or和not。逻辑运算符可以对两个数据逻辑运算。Python的逻辑运算符见表5-6(其中,a=10,b=10)。
表5-6 逻辑运算符

【例5-21】逻辑运算符及表达式举例。

程序运行结果如图5-21所示。

图5-21 逻辑运算符举例结果
5.3.5 按位运算符

按位运算符是把数字看作二进制来进行计算的。
Python的按位运算符见表5-7。表5-7中变量a为60,b为13,二进制格式如下。

表5-7 按位运算符

【例5-22】按位运算符及表达式举例。

程序运行结果如图5-22所示。

图5-22 按位运算符举例结果
5.3.6 成员运算符

成员运算符有in和not in,它们可以确定一个值是否是另一个值的成员。Python的成员运算符见表5-8。
表5-8 成员运算符

【例5-23】成员运算符及表达式举例。

程序运行结果如图5-23所示。

图5-23 成员运算符举例结果
5.3.7 身份运算符

身份运算符有is和is not。Python的身份运算符见表5-9。
表5-9 身份运算符

【例5-24】身份运算符及表达式举例。

程序运行结果如图5-24所示。

图5-24 身份运算符举例结果
5.3.8 Python运算符优先级

Python有很多运算符,这些运算符的优先级顺序是什么样的呢?表5-10列出了从最高到最低优先级的所有运算符。
表5-10 Python运算符优先级
