Python3 运算符

Arithmetic, comparison chaining, bitwise, logical, membership and identity operators.

Beginner
Key Points`==` compares values, `is` compares identity; `and`/`or` return operands, not booleans.

Arithmetic

OperatorMeaningExample
+ - *Add, subtract, multiply2 * 3 -> 6
/True division, always float7 / 2 -> 3.5
//Floor division, rounds down-7 // 2 -> -4
%Modulo, sign follows divisor-7 % 3 -> 2
**Power2 ** 10 -> 1024
:=Walrus: assign inside expressionif (n := len(s)) > 3:
Python
print(7 / 2, 7 // 2, 7 % 2)   # 3.5 3 1
print(-7 // 2, -7 % 2)        # -4 1

# 海象运算符:少写一次调用
data = "abcdef"
if (n := len(data)) > 5:
    print(f"too long: {n}")

Comparison Chaining

Python allows mathematical chaining: 0 < x < 10 means 0 < x and x < 10, and x is evaluated only once.

Python
age = 25
print(18 <= age < 60)          # True
print(1 < 2 < 3 < 4)           # True

Bitwise

OperatorMeaningExample
&AND0b1100 & 0b1010 -> 8
|OR0b1100 | 0b1010 -> 14
^XOR0b1100 ^ 0b1010 -> 6
~NOT: ~x == -x-1~5 -> -6
<< >>Shift left / right1 << 10 -> 1024
Python
# 权限位:读 4 / 写 2 / 执行 1
READ, WRITE, EXEC = 4, 2, 1
perm = READ | WRITE                 # 6
print(bool(perm & WRITE))           # True
perm &= ~WRITE                      # 撤销写权限 -> 4
print(bin(perm))

Logical, Membership, Identity

OperatorReturnsNote
and / orAn operand, not a boola or b is a if a is truthy
notAlways a boolnot [] -> True
in / not inboolWorks on str, list, dict, set
is / is notboolCompares identity (same object)
Python
name = input("name: ") or "anonymous"   # 空输入时取默认值
print("py" in "python", 3 in [1, 2, 3]) # True True

a = [1, 2, 3]
b = [1, 2, 3]
print(a == b, a is b)          # True False —— 值相等但不是同一对象
print(a is None, a == None)    # False False —— 判空请用 is None
Only use is for None, True, False and sentinel objects. Comparing strings with is sometimes works by interning and then breaks in production.

Precedence

  1. ** — power (right associative)
  2. * / // % then + -
  3. << >> then & then ^ then |
  4. Comparisons, in, is, not
  5. and then or then :=
When in doubt, add parentheses. a and b or c is not a ternary — it breaks when b is falsy.

Friends & Partners