- Python+Excel职场办公数据分析
- 王红明 张鸿斌编著
- 907字
- 2025-02-18 00:35:09
2.4 运算符
运算符是一些特殊的符号,主要用于数学计算、比较大小和逻辑运算等。Python的运算符主要包括算术运算符、赋值运算符、比较运算符、逻辑运算符和位运算符等。使用运算符将所用的数据按照一定的规则连接起来的式子,称为表达式。使用算术运算符连接起来的式子称为算术表达式。
2.4.1 算术运算符

算术运算符是处理四则运算的符号,在数字的处理中应用得最多。Python支持所有的基本算术运算符,见表2-2。
表2-2 Python常用算术运算符

如下为几种算术运算。

案例3:计算学生平均分数
在IDLE中创建一个名为“分数.py”的文件,然后在文件中定义三个变量,分别用于记录学生的数学、语文、英语分数,然后根据公式计算平均分数:平均分数=(数学分数+语文分数+英语分数)/3。代码如下。

运行结果如下。

2.4.2 比较运算符

比较运算符,也称为关系运算符,用于对常量、变量或表达式的结果进行大小、真假等比较,如果比较结果为真,则返回True(真);反之,则返回False(假)。比较运算符通常用在条件语句中作为判断的依据。Python支持的比较运算符见表2-3。
表2-3 Python比较运算符

如下为比较运算符的用法

案例4:判断成绩是否优异
在IDLE中创建一个名为“成绩.py”的文件,然后在文件中定义一个变量,用于记录学生成绩,然后用if语句判断成绩是否优异。代码如下。

运行结果如下。

2.4.3 逻辑运算符
逻辑运算符是对真和假两种布尔值进行运算(操作bool类型的变量、常量或表达式),逻辑运算的返回值也是bool类型值。
Python中的逻辑运算符主要包括and(逻辑与)、or(逻辑或)以及not(逻辑非),它们的具体用法和功能见表2-4。
表2-4 Python逻辑运算符及功能

2.4.4 赋值运算符
赋值运算符主要用来为变量(或常量)赋值,在使用时,既可以直接用基本赋值运算符“=”将右侧的值赋给左侧的变量,右侧也可以在进行某些运算后再赋值给左侧的变量。
“=”赋值运算符还可与其他运算符(算术运算符、位运算符等)结合,成为功能更强大的赋值运算符,见表2-5。
表2-5 Python常用赋值运算符

2.4.5 运算符的优先级
所谓运算符的优先级,是指在应用中哪一个运算符先计算,哪一个后计算。Python中运算符的运算规则是优先级高的运算先执行,优先级低的运算后执行,统一优先级的操作按从左到右的顺序进行。表2-6按从高到低的顺序列出了运算符的优先级。
表2-6 运算符的优先级

(续)
