Python运算符详解:比较、逻辑、位运算与优先级

不晚
不晚
发布时间:2026-10-16 | 3人浏览过
原创

本文深入解析Python中的各类运算符。涵盖比较运算符的标识与值判断、布尔运算符(and/or/not/in)的逻辑行为、位运算规则以及运算符优先级表。通过具体代码示例与输出结果,帮助开发者准确理解并应用Python运算符号,避免常见逻辑错误。

比较运算符


a,b=10,30
print('a>b吗?',a>b)
print('a<b吗?',a<b)
print('a<=b吗?',a>=b)
print(a is b)#这个比较的是id标识

a>b吗? False
a<b吗? True
a<=b吗? False
False

在Python中,每个变量包含三个核心要素:标识(identity)、类型(type)和值(value)。当使用 is 运算符比较对象时,实际上是在比较它们的标识,即判断两个变量是否指向内存中的同一个对象。

布尔运算符


print(a==1 and b==2)#ture and true-->ture
print(a==1 and b<2)#ture and false-->false
print(a!=1 and b==2)#false and ture-->false
print(a!=1 and b!=2)#false and false -->false
print('---------------or 或者-----------------------------------------')
print(a==1 or b==2)#ture or true-->ture
print(a==1 or b<2)#ture or false-->ture
print(a!=1 or b==2)#false or ture-->ture
print(a!=1 or b!=2)#false and false -->false
print('---------------not 对运算数取反-----------------------------------------')
f=True
f2=False
print(not f)
print(not f2)
print('---------------in 与not in-----------------------------------------')
s='helloworld'
print('w'in s)
print('k'in s)
print('w'not in s)
print('k'not in s)

True
True
False
False
False
---------------or 或者-----------------------------------------
True
True
True
False
---------------not 对运算数取反-----------------------------------------
False
True
---------------in 与not in-----------------------------------------
True
False
False
True

Python支持多种位运算符,用于对整数进行逐位操作。


了解运算符的优先级对于编写正确的表达式至关重要,不同运算符具有不同的执行顺序。



至此,关于Python运算符号的详细介绍已完毕。如需了解更多Python运算符相关内容,建议搜索本站过往文章或继续阅读后续相关教程。感谢大家的支持!

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表