- 人工智能开发语言:Python
- 潘风文 潘启儒
- 1003字
- 2025-02-18 05:29:21
3.4 运算符和表达式
3.4.1 算术运算
Python中的算术表达式与其他语言基本一致,常用算术表达式见表3-18。
表3-18 常用算术表达式

另外再介绍两种算术运算表达式。
1)取整除法(//)
包括向上取整、向下取整、向零取整。向上取整时,所取整数大于实际值,如:
7.8//3==3.0
7.8//-3==-2.0
向下取整时,所取整数小于实际值,如:
7.8//3==2.0
-7.8//3==-3.0
向零取整时,所取整数的绝对值小于实际值的绝对值,如:
7.8//3==2.0
-7.8//3==-2.0
Python采用的是向下取整的方式,这点需要读者注意。
2)取模(%)
又称取余,计算两个变量取整除法(//)后的余数,计算公式为:
remainder = x – (x//y)*y,其中x为被除数,y为除数。
举例如下:


输出结果如下:

注意:在不同语言中,取模计算的方法可能不同。
3.4.2 关系运算符
关系运算符也称比较运算符,其结果为一般布尔值(True或者False),见表3-19。
表3-19 关系运算符

3.4.3 赋值运算
Python中的赋值运算表达式见表3-20。
表3-20 赋值运算表达式

3.4.4 逻辑运算
Python语言支持的逻辑运算包括与、或、非三种,表达式见表3-21。
表3-21 逻辑运算表达式

注意:数值0、空字符串、空元组、空集合、空列表、空字典、None值相当于布尔值False。举例如下:


输出结果如下:

3.4.5 位运算
位运算是以二级制数的位为对象的运算方法。Python中位运算包括位与(&)、位或(|)、位异或(^)以及位取反(~)、位左移(<<)、位右移(>>)等,见表3-22。
表3-22 位运算

为了更清楚地说明以上运算符的作用,下面举例说明。

输出结果如下:

Python中的左移运算与C/C++、Java等语言有区别,造成这一问题的原因在于Python把int类型的数值视为无精度类型,不会发生溢出而进行截取的情况。解决这个问题的方法有两种:一种是在Python中自己编写一个函数,模拟其他语言的规则来实现左移;另外一种是使用其他语言实现左移,然后在Python中调用。
3.4.6 身份运算
身份运算用来比较两个对象的内存位置(内存地址),常用的有两个,见表3-23。
表3-23 身份运算

身份运算(is)与比较运算(==)之间的主要区别是,is 用于判断两个变量引用对象是否为同一个, == 用于判断引用变量的值(内容)是否相等。例如:


输出结果如下:

3.4.7 成员运算
成员运算用来判断某个变量是否为某个序列变量的子成员。序列变量可以是字符串、元组、列表等类型变量,见表3-24。
表3-24 成员运算

实例说明:

输出结果如下:

可以看出,操作符左边的变量也可以为元组、列表等类型。
3.4.8 运算符优先级
表3-25按照从优先级从高到低的顺序列出了Python中的各种运算符。
表3-25 运算符优先级

运算符的优先级顺序必须牢记,如果一时不明确,可以使用小括号把需要一起计算的片段包围起来,这样小括号内的片段会被当做一个整体来对待,如下面实例:
