Python 运算符有哪些你清楚吗
前言
每种语言都有运算符,大多数意义相似,但也有各自的差异。今天就来说说 python 的运算符。
python 有哪些运算符
运算符是用来对数字进行数学运算,比如我们耳熟能详的加减乘除。在 python 中也支持这些运算符,按类型可分为:
算术运算符
关系运算符
逻辑运算符
赋值运算符
位运算符
算术运算符

算术运算符较简单,不多做介绍。需要注意的是 python 的除法在 python2 和 python3 的差异。在 python2 中除法是直接取整,而 python3 的除法才是我们数学运算的除法。
复制代码
复制代码
关系运算符

比较运算符在我们代码中也很常见,比如判断 2 个变量是否相等,某个数字是否小于预期的数字等。
逻辑运算符

其实逻辑运算符可以用来操作任意类型的判断,执行结果不一定是 bool 类型。比如:
复制代码
其实就是 and 在判断两边对象时,如果第一个真,就接着判断第二个。这里两边都为真,就返回第二个的值;若第一个为 False(0 也是 False),那就直接返回 False 了。
复制代码
赋值运算符

赋值运算符其实就是一种简写的算术运算符,习惯了写法即可。
位运算符
位运算符就是将数字转为计算机的二进制来计算

小结
本文总结了一下 python 中的运算符。虽说大部分都很简单,但是部分运算符需要清楚特性和注意点,比如除法在 python2 和 python3 的区别。
版权声明: 本文为 InfoQ 作者【芥末拌个饭吧】的原创文章。
原文链接:【http://xie.infoq.cn/article/d48a98b231baf1538846c7516】。文章转载请联系作者。
评论