Python 运算符完全指南:算术、逻辑、比较、赋值、位运算与优先级
Python 逻辑运算符
Python 逻辑运算符评估布尔表达式,返回 True 或 False。三大逻辑运算符为 and、or、not,是 if、while 等条件语句控制流的核心。
本教程覆盖 Python 全谱系运算符:
- 算术运算符
- 比较运算符
- 赋值运算符
- 逻辑与位运算符
- 成员运算符
- 身份运算符
- 运算符优先级
算术运算符
执行数值计算。支持:+ 加、- 减、* 乘、/ 真除、// 地板除、% 取模、** 幂。可直接用于表达式或配合 eval() 动态求值。
示例:简单加法
x = 4 y = 5 print(x + y) # 输出: 9
其他类似:4 * 5 得 20,4 / 2 得 2.0,4 ** 2 得 16。
比较运算符
比较(关系)运算符评估两值关系,返回布尔值。包括:
==等于!=不等于<小于<=小于等于>大于>=大于等于
示例:比较两变量
x = 4
y = 5
print('x > y is', x > y) # 输出: False
赋值运算符
将值存入变量。基本形式 =,复合运算符结合运算与赋值:+=、-=、*=、/=、**=。
示例:基本与复合赋值
num1 = 4
num2 = 5
print('Line 1 - Value of num1:', num1)
print('Line 2 - Value of num2:', num2)
# 复合加法
res = num1 + num2
res += num1
print('Line 3 - Result after res += num1:', res) # 输出: 13
逻辑与位运算符
逻辑运算符(and、or、not)评估布尔表达式。位运算符(&、|、^、~、<<、>>)执行位级操作。
示例:逻辑运算
a = True
b = False
print('a and b is', a and b) # False
print('a or b is', a or b) # True
print('not a is', not a) # False
成员运算符
测试值是否在序列中:in 和 not in。
示例:检查列表成员
x = 4
y = 8
sample_list = [1, 2, 3, 4, 5]
if x in sample_list:
print('Line 1 - x is available in the list')
else:
print('Line 1 - x is not available in the list')
if y not in sample_list:
print('Line 2 - y is not available in the list')
else:
print('Line 2 - y is available in the list')
身份运算符
比较对象内存地址:is 和 is not。区分值相等但身份不同的对象至关重要。
示例:身份比较
x = 20
y = 20
if x is y:
print('x & y have the same identity')
y = 30
if x is not y:
print('x & y have different identities')
运算符优先级
Python 遵循严格优先级层级解析无括号表达式。最高幂运算 (**),其次一元运算符、乘除模、加减、比较、身份、成员、逻辑、最后赋值。括号可覆盖默认优先级使表达式显式化。
示例:优先级实战
v = 4
w = 5
x = 8
y = 2
z = (v + w) * x / y
print('Value of (v + w) * x / y is', z) # 输出: 28.0
Python 2 兼容示例
下面是 Python 2 等价片段(print 语句无括号)。
# 算术运算符 x = 4; y = 5; print x + y # 比较运算符 x = 4; y = 5; print 'x > y is', x > y # 赋值运算符 num1 = 4; num2 = 5; print 'Line 1 - Value of num1:', num1; print 'Line 2 - Value of num2:', num2 # 复合赋值 num1 = 4; num2 = 5; res = num1 + num2; res += num1; print 'Line 3 - Result after res += num1:', res # 逻辑运算符 a = True; b = False; print 'a and b is', a and b; print 'a or b is', a or b; print 'not a is', not a # 成员运算符 x = 4; y = 8; sample_list = [1,2,3,4,5] if x in sample_list: print 'Line 1 - x is available in the list' else: print 'Line 1 - x is not available in the list' if y not in sample_list: print 'Line 2 - y is not available in the list' else: print 'Line 2 - y is available in the list' # 身份运算符 x = 20; y = 20 if x is y: print 'x & y have the same identity' y = 30 if x is not y: print 'x & y have different identities' # 优先级 v = 4; w = 5; x = 8; y = 2; z = (v + w) * x / y; print 'Value of (v + w) * x / y is', z
总结
- 算术运算符处理数值计算。
- 比较运算符判断关系真值。
- 赋值运算符存值;复合变体结合运算。
- 逻辑运算符控制流程;位运算符操作位。
- 成员运算符测试序列包含。
- 身份运算符比较对象标识。
- 优先级决定求值顺序;括号可覆盖。
Python