Back to series
· 13 min read

Python Operators and Expressions


I. What Are Operators and Expressions

An operator is a symbol or keyword used to perform a specific operation, such as +, -, *, and, in.

An operand is the data that an operator processes; it can be a variable, a constant, a function call, or another expression.

An expression is a syntactic structure composed of operands, operators, and possibly function calls. After evaluation, an expression produces a result.

For example:

a = 10
b = 3

result = a + b * 2

print(result)  # 16

Where:

  • a, b, and 2 are operands.
  • + and * are operators.
  • b * 2 is an expression.
  • a + b * 2 is a larger expression.
  • The result of evaluating the whole expression is the integer 16.

1. The Relationship Between Operators and Expressions

Operators define how operands are processed, while expressions organize those operations together.

price = 100
quantity = 3

total = price * quantity

Here:

  • price and quantity are operands.
  • * is the multiplication operator.
  • price * quantity is an expression.
  • total = price * quantity is an assignment statement, whose right-hand side contains an expression.

It is necessary to distinguish expressions from statements:

Concept Meaning Example
Expression Produces a result when evaluated a + b
Statement Performs a complete program operation a = 10
Assignment statement Binds the result of an expression to a target name total = a + b
Function call expression Calls a function and obtains its return value len("Python")

In Python, expressions can be nested inside statements, and statements are responsible for organizing the execution of the program.

II. Categories of Python Operators

Python provides many kinds of operators, which can be divided by function into the following categories:

Operator category Main use Representative operators
Arithmetic operators Numeric computation +, -, *, /
Comparison operators Compare two values ==, !=, >, <
Logical operators Combine conditional tests and, or, not
Assignment operators Bind or update variables =, +=, *=
Bitwise operators Operate on the binary bits of integers &, |, ^
Membership operators Test whether an element belongs to a container in, not in
Identity operators Test whether two references point to the same object is, is not
Conditional expression Choose a result based on a condition x if condition else y
Walrus operator Assign within an expression :=

Different categories of operators follow different operating rules and may impose different requirements on the types of their operands.

III. Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations and are the most commonly used operators in Python.

1. Basic Arithmetic Operators

Operator Name Example Result
+ Addition 10 + 3 13
- Subtraction 10 - 3 7
* Multiplication 10 * 3 30
/ Division 10 / 3 3.333...
// Floor division 10 // 3 3
% Modulo 10 % 3 1
** Exponentiation 2 ** 3 8

Example:

a = 10
b = 3

print(a + b)   # 13
print(a - b)   # 7
print(a * b)   # 30
print(a / b)   # 3.3333333333333335
print(a // b)  # 3
print(a % b)   # 1
print(a ** b)  # 1000

2. Addition and Subtraction

+ and - are used to perform addition and subtraction.

x = 20
y = 8

print(x + y)  # 28
print(x - y)  # 12

For numbers, + means addition; for strings and sequences, + can also mean concatenation.

print("Hello " + "Python")
# Hello Python

print([1, 2] + [3, 4])
# [1, 2, 3, 4]

The exact behavior of an operator depends on the types of its operands and the operation protocols they implement.

3. Multiplication

* is used to multiply numbers, and can also be used to repeat sequences.

print(4 * 5)
# 20

print("Python " * 3)
# Python Python Python

print([1, 2] * 3)
# [1, 2, 1, 2, 1, 2]

Note that when you repeat a list containing mutable objects, the objects themselves are not copied.

matrix = [[0] * 3] * 2

matrix[0][0] = 9

print(matrix)
# [[9, 0, 0], [9, 0, 0]]

This is because the two outer elements reference the same inner list.

A safer way to write it:

matrix = [[0] * 3 for _ in range(2)]

matrix[0][0] = 9

print(matrix)
# [[9, 0, 0], [0, 0, 0]]

4. Division /

/ means true division.

For built-in integer operands, the result of division is usually a float, even when the division is exact.

print(10 / 2)
# 5.0

print(7 / 2)
# 3.5

Therefore:

print(type(10 / 2))
# <class 'float'>

In scenarios involving money, precision, or large integers, you need to be aware of the precision limits of floating-point representation.

5. Floor Division //

// means division that rounds toward negative infinity (floor division), not simply truncating the fractional part.

print(10 // 3)
# 3

print(-10 // 3)
# -4

print(10 // -3)
# -4

Negative numbers are especially error-prone:

print(int(-10 / 3))
# -3

print(-10 // 3)
# -4

The two results differ:

  • int() truncates toward zero when converting a float.
  • // rounds the quotient toward negative infinity.

6. Modulo %

% is used to compute the remainder.

print(10 % 3)
# 1

print(10 % 2)
# 0

In Python, the modulo operation satisfies:

a == (a // b) * b + (a % b)

For a nonzero integer divisor, the remainder has the same sign as the divisor, or the remainder is zero.

print(10 % 3)
# 1

print(-10 % 3)
# 2

print(10 % -3)
# -2

print(-10 % -3)
# -1

The modulo operation is commonly used to:

  • Determine whether a number is odd or even.
  • Cycle through indices.
  • Perform periodic tasks.
  • Convert time.
  • Map values within a fixed range.

For example, to determine whether a number is odd or even:

number = 17

if number % 2 == 0:
    print("偶数")
else:
    print("奇数")

Note that the divisor cannot be zero; otherwise, a ZeroDivisionError will be raised.

7. Exponentiation **

** is used to calculate powers.

print(2 ** 3)
# 8

print(5 ** 2)
# 25

print(9 ** 0.5)
# 3.0

Exponentiation also supports negative exponents:

print(2 ** -2)
# 0.25

Exponentiation has high precedence and is right-associative:

print(2 ** 3 ** 2)
# 512

It is calculated as:

print(2 ** (3 ** 2))
# 512

rather than:

print((2 ** 3) ** 2)
# 64

8. Unary plus and minus operators

+ and - can also be used as unary operators.

number = 10

print(+number)
# 10

print(-number)
# -10

The unary plus sign usually represents the value itself, while the unary minus sign represents its negation.

IV. Comparison Operators

Comparison operators are used to compare whether two objects are equal or to determine their relative order.

The result of a comparison expression is usually a Boolean value, True or False.

1. Basic Comparison Operators

Operator Meaning Example Result
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 5 > 3 True
< Less than 3 < 5 True
>= Greater than or equal to 5 >= 5 True
<= Less than or equal to 3 <= 5 True

Example:

a = 10
b = 20

print(a == b)  # False
print(a != b)  # True
print(a > b)   # False
print(a < b)   # True
print(a >= 10) # True
print(b <= 20) # True

2. Equality Comparison ==

== is used to determine whether the values of two objects are equal.

a = [1, 2, 3]
b = [1, 2, 3]

print(a == b)
# True

Although the two lists are different objects, their contents are the same, so the comparison result is True.

3. Inequality Comparison !=

!= is used to determine whether the values of two objects are not equal.

print(10 != 20)
# True

print("Python" != "Java")
# True

4. Ordering Comparisons

>, <, >=, and <= are used to determine the ordering relationship between objects.

age = 20

print(age >= 18)
# True

Different types do not necessarily support ordering comparisons.

# The following expression will raise a TypeError
# print(10 < "20")

Python does not automatically convert arbitrary strings to numbers for ordering comparisons like some languages do.

5. Chained Comparisons

Python supports chained comparisons, allowing multiple comparison operators to be used in succession.

age = 25

print(18 <= age <= 60)
# True

It is equivalent to:

18 <= age and age <= 60

However, the two are not a simple textual substitution: chained comparisons evaluate the middle expression only once.

def get_number():
    print("函数被调用")
    return 20

result = 10 < get_number() < 30

print(result)

get_number() is called only once.

Chained comparisons are well suited to expressing range checks, numeric intervals, and consecutive constraints.

score = 85

if 0 <= score <= 100:
    print("成绩有效")

6. Special Cases in Comparison Operations

Floating-point comparisons require attention to precision issues.

print(0.1 + 0.2 == 0.3)
# False

This is because floating-point numbers use binary approximations, and some decimal fractions cannot be represented exactly.

For numeric values that require tolerance-based comparison, you can use math.isclose():

import math

print(math.isclose(0.1 + 0.2, 0.3))
# True

5. Logical Operators

Logical operators are used to combine multiple conditional expressions. They mainly include:

  • and: logical AND.
  • or: logical OR.
  • not: logical NOT.

1. Logical AND and

When both operands are truthy, and returns the right-hand operand; otherwise, it returns the first falsy operand.

print(True and True)
# True

print(True and False)
# False

print(False and True)
# False

In conditional checks, it is commonly used to indicate that multiple conditions must all hold at the same time.

age = 25
has_ticket = True

if age >= 18 and has_ticket:
    print("允许进入")

Note that and does not necessarily return a Boolean value.

print("Python" and 100)
# 100

print(0 and 100)
# 0

2. Logical OR or

or evaluates from left to right and returns the first truthy operand it encounters; if all preceding operands are falsy, it returns the last operand.

print(True or False)
# True

print(False or True)
# True

print(False or False)
# False

Example:

username = ""
display_name = username or "匿名用户"

print(display_name)
# 匿名用户

Likewise, or does not necessarily return a Boolean value:

print("" or "默认值")
# 默认值

print("Python" or "默认值")
# Python

3. Logical NOT not

not negates the truth value of its operand, and the result is always a Boolean value.

print(not True)
# False

print(not False)
# True

print(not 0)
# True

print(not "Python")
# False

4. Truthiness and Logical Operations

Python supports truth-value testing of objects.

Common falsy values include:

  • False
  • None
  • numeric zero, such as 0, 0.0, 0j
  • empty string ""
  • empty list []
  • empty tuple ()
  • empty dictionary {}
  • empty set set()

Most other objects are truthy.

items = []

if not items:
    print("列表为空")

Logical operators do not require their operands to be of type bool; instead, they use the object's truth-value testing rules.

5. Short-Circuit Evaluation

Short-circuit evaluation (Short-Circuit Evaluation) is an important feature of Python logical operations.

and and or evaluate from left to right and decide whether to continue evaluating subsequent operands based on the current result.

  • and: if the left side is false, the right side is not evaluated.
  • or: if the left side is true, the right side is not evaluated.
def check():
    print("执行了 check")
    return True

print(False and check())
# False

print(True or check())
# True

Neither call executes check().

Short-circuit evaluation can avoid unnecessary computation and can also be used for safety checks.

user = None

if user is not None and user.is_active:
    print("用户有效")

Because user is not None is false, the following user.is_active is not accessed, so AttributeError is not raised.

Short-circuit evaluation flow:

flowchart TD
    A["开始计算逻辑表达式"] --> B["计算左侧操作数"]
    B --> C{"运算符类型"}
    C -->|"and"| D{"左侧是否为真"}
    C -->|"or"| E{"左侧是否为真"}
    D -->|"否"| F["返回左侧操作数"]
    D -->|"是"| G["计算右侧操作数"]
    E -->|"是"| H["返回左侧操作数"]
    E -->|"否"| G
    G --> I["返回右侧操作数"]
    F --> J["表达式结束"]
    H --> J
    I --> J

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style I fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style J fill:#E0F0FE,stroke:#93BCE8,color:#1E4976

6. Assignment Operators

Assignment operators are used to bind objects to variable names or to update the binding of an existing variable.

1. Basic Assignment =

name = "Python"
age = 30
price = 99.9

Assignment in Python is not simply copying a value into the memory location where the variable resides; rather, it establishes a binding relationship between a name and an object.

a = [1, 2, 3]
b = a

b.append(4)

print(a)
# [1, 2, 3, 4]

a and b point to the same list object, so changes made to the list through b are also observable through a.

2. Compound Assignment Operators

Compound assignment operators combine an operation and an assignment.

Operator Equivalent form (conceptually)
+= a = a + b
-= a = a - b
*= a = a * b
/= a = a / b
//= a = a // b
%= a = a % b
**= a = a ** b
&= a = a & b
|= a = a | b
^= a = a ^ b
>>= a = a >> b
<<= a = a << b
@= a = a @ b

Example:

count = 10

count += 5
print(count)
# 15

count *= 2
print(count)
# 30

count -= 10
print(count)
# 20

3. Differences Between Compound Assignment and Ordinary Assignment

Compound assignment is not always completely equivalent to the corresponding ordinary assignment.

For example, lists support in-place extension:

a = [1, 2]
b = a

a += [3]

print(a)
# [1, 2, 3]

print(b)
# [1, 2, 3]

But when using ordinary addition and assignment:

a = [1, 2]
b = a

a = a + [3]

print(a)
# [1, 2, 3]

print(b)
# [1, 2]

The difference is:

  • += usually performs in-place extension on lists.
  • a = a + [...] usually creates a new list and then rebinds a to the new object.

This is because compound assignment may call the object's in-place operation method, such as __iadd__(); if the object does not implement the corresponding method, it may fall back to the ordinary operation and assignment mechanism.

4. Chained Assignment

Python supports assigning values to multiple variables at the same time:

a = b = c = 100

print(a, b, c)
# 100 100 100

Chained assignment binds multiple names to the same object.

For immutable integers, this usually poses no obvious problem; for mutable objects, special care is required:

a = b = []

a.append(1)

print(a)
# [1]

print(b)
# [1]

If you want to create two independent lists, create them separately:

a = []
b = []

5. Unpacking Assignment

Unpacking assignment allows multiple values to be assigned to multiple variables at once.

x, y = 10, 20

print(x)
# 10

print(y)
# 20

It can also be used to swap variables:

a = 10
b = 20

a, b = b, a

print(a, b)
# 20 10

Python first evaluates the expression on the right side, then performs the target assignment.

Unpacking assignment also supports starred collection:

first, *middle, last = [1, 2, 3, 4, 5]

print(first)
# 1

print(middle)
# [2, 3, 4]

print(last)
# 5

VII. Bitwise Operators

Bitwise operators are used to directly manipulate the binary bits of integers.

They are commonly used in low-level development, permission flags, protocol parsing, state management, and performance-sensitive numerical processing.

1. Basics of Bitwise Operations

Integers can be represented in binary form.

For example:

Decimal 5  = Binary 0101
Decimal 3  = Binary 0011

Bitwise operations perform the specified operation bit by bit.

2. Bitwise AND &

The result is 1 only when both corresponding binary bits are 1.

a = 5
b = 3

print(a & b)
# 1

Calculation process:

0101
0011
----
0001

3. Bitwise OR |

As long as at least one of the two corresponding binary bits is 1, the result is 1.

print(5 | 3)
# 7
0101
0011
----
0111

4. Bitwise XOR ^

When the two corresponding binary bits are different, the result is 1; when they are the same, the result is 0.

print(5 ^ 3)
# 6
0101
0011
----
0110

5. Bitwise NOT ~

~ performs bitwise NOT on an integer.

Python integers use signed mathematical integer semantics, and bitwise NOT satisfies:

~x == -x - 1

For example:

print(~5)
# -6

print(~0)
# -1

It cannot simply be understood as flipping each bit of a fixed-length binary number, because Python integers do not have a fixed machine word-width limit.

6. Left Shift <<

The left shift operation moves the binary bits of an integer to the left by a specified number of positions.

print(5 << 1)
# 10

print(5 << 2)
# 20

For non-negative integers, shifting left by one position is equivalent to multiplying by 2.

7. Right Shift >>

The right shift operation moves the binary bits of an integer to the right by a specified number of positions.

print(20 >> 1)
# 10

print(20 >> 2)
# 5

For non-negative integers, shifting right by one position is equivalent to integer division by 2.

When right-shifting negative numbers, Python uses arithmetic right-shift semantics, and the result is equivalent to dividing by 2^n with rounding toward negative infinity.

8. Comprehensive Bitwise Operations Example

a = 12
b = 10

print(a & b)   # 8
print(a | b)   # 14
print(a ^ b)   # 6
print(~a)      # -13
print(a << 1)  # 24
print(a >> 1)  # 6

9. Bitmasks and Permission Control

Bitwise operations are very useful in permission management and status flags.

Suppose the system has three permissions:

READ = 1      # 0001
WRITE = 2     # 0010
EXECUTE = 4   # 0100

Permissions can be combined using bitwise OR:

permissions = READ | WRITE

print(permissions)
# 3

Check permissions using bitwise AND:

if permissions & READ:
    print("具有读取权限")

Add permissions using bitwise OR:

permissions |= EXECUTE

Remove permissions using bitwise AND and NOT:

permissions &= ~WRITE

This approach compresses multiple boolean states into a single integer and is suitable for handling flags and permission sets.

VIII. Membership Operators

Membership operators are used to determine whether one object is contained in another object.

Python provides:

  • in
  • not in

1. in

Determines whether an element exists in the target object.

numbers = [1, 2, 3, 4]

print(3 in numbers)
# True

print(8 in numbers)
# False

Strings also support membership tests:

text = "Hello Python"

print("Python" in text)
# True

print("Java" in text)
# False

For dictionaries, membership tests check keys by default, not values:

user = {
    "name": "Alice",
    "age": 25
}

print("name" in user)
# True

print("Alice" in user)
# False

If you need to check whether a value exists, use:

print("Alice" in user.values())
# True

2. not in

Tests whether an element does not exist in the target object.

numbers = [1, 2, 3]

print(5 not in numbers)
# True

3. Membership Test Efficiency Across Containers

Membership tests in different containers generally have different time complexities.

Data Structure Typical Membership Test Complexity
List list O(n)
Tuple tuple O(n)
Set set O(1) on average
Dictionary dict O(1) on average

Therefore, if you need to frequently check whether an element exists, consider using a set or a dictionary.

allowed_users = {"Alice", "Bob", "Charlie"}

if "Alice" in allowed_users:
    print("允许访问")

The complexity here is the average case under common implementations, and does not mean O(1) is guaranteed in all cases.

9. Identity Operators

Identity operators are used to determine whether two references point to the same object.

Python provides:

  • is
  • is not

1. is

is is used to determine whether two names reference the same object.

a = [1, 2, 3]
b = a
c = [1, 2, 3]

print(a is b)
# True

print(a is c)
# False

Although a and c have the same content, they are two separate list objects.

2. is not

is not is used to determine whether two names reference different objects.

a = [1, 2]
b = [1, 2]

print(a is not b)
# True

3. The Difference Between == and is

This is a very important set of concepts in Python.

Operator What It Tests Focus
== Whether the values are equal Object content or equality rules
is Whether they are the same object Object identity
!= Whether the values are not equal Object content or equality rules
is not Whether they are not the same object Object identity

Example:

a = [1, 2, 3]
b = [1, 2, 3]

print(a == b)
# True

print(a is b)
# False

4. Why You Should Use is When Testing for None

In Python, None is a singleton object.

To check whether a variable is None, the recommended approach is:

value = None

if value is None:
    print("没有值")

Not recommended:

if value == None:
    print("没有值")

The reason is that == can be overloaded by custom objects, whereas is tests object identity and is not affected by custom __eq__() logic.

Correct habit:

if result is None:
    pass

if result is not None:
    pass

5. Don't Rely on Object Caching to Test Identity

Some objects, such as certain integers and strings, may be cached or reused by the interpreter.

a = 100
b = 100

print(a is b)

In some environments this may yield True, but that does not mean you should use is to test whether numbers are equal.

Object caching, interning, and memory reuse are implementation details and should not be used as the basis for judging business logic.

10. Conditional Expressions

A conditional expression (Conditional Expression) allows you to choose between different results based on a condition within a single expression.

Basic syntax:

value_if_true if condition else value_if_false

Example:

age = 20

status = "成年人" if age >= 18 else "未成年人"

print(status)
# Adult

It is equivalent to:

if age >= 18:
    status = "成年人"
else:
    status = "未成年人"

1. Execution Mechanism of Conditional Expressions

A conditional expression evaluates only the selected branch.

def success():
    print("执行成功分支")
    return "成功"

def failure():
    print("执行失败分支")
    return "失败"

result = success() if True else failure()

Only success() will be called.

2. Nested Conditional Expressions

Python allows nested conditional expressions:

score = 85

level = (
    "优秀" if score >= 90
    else "良好" if score >= 80
    else "及格" if score >= 60
    else "不及格"
)

print(level)
# Good

However, too much nesting reduces readability.

For complex business logic, ordinary if / elif / else statements should be preferred.

11. The Walrus Operator :=

The walrus operator (Assignment Expression) was introduced in Python 3.8 and is also called an assignment expression.

It allows an assignment to be performed inside an expression, and the assigned value becomes the result of the expression.

1. Basic Syntax

name := expression

Example:

if (length := len("Python")) > 5:
    print(length)
# 6

This does two things:

  1. Evaluate len("Python").
  2. Bind the result to length and use that result for the conditional check.

2. Reducing Duplicate Computation

Without the walrus operator:

text = "Python"

if len(text) > 5:
    print(len(text))

With the walrus operator:

if (length := len("Python")) > 5:
    print(length)

When the result of an expression needs to be used after the condition check, the walrus operator can reduce duplicate computation.

3. Using It in a while Loop

while (line := input("请输入内容:")) != "quit":
    print("输入内容:", line)

The input result is assigned to line and is also used to determine whether the loop should continue.

4. Using It in List Comprehensions

numbers = ["10", "20", "abc", "30"]

results = [
    value
    for item in numbers
    if (value := int(item)) > 15
]

However, the code above will raise ValueError when it encounters "abc". If the input is untrusted, you need to validate it first or use exception handling.

For example:

numbers = ["10", "20", "abc", "30"]

results = []

for item in numbers:
    try:
        value = int(item)
    except ValueError:
        continue

    if value > 15:
        results.append(value)

print(results)
# [20, 30]

5. Cautions for Using the Walrus Operator

  • It is an assignment within an expression, not a replacement for ordinary assignment statements.
  • Parentheses are required in some syntactic positions.
  • When used in comprehensions, there are scoping and syntax restrictions.
  • Do not overuse it just to save a line of code.
  • If the assignment relationship is not intuitive enough, ordinary assignment statements are usually clearer.

12. Matrix Multiplication Operator @

Python uses @ to represent the matrix multiplication operator.

This operator was introduced in Python 3.5 and is mainly used in matrix calculations and scientific computing.

A @ B

For built-in ordinary numbers, @ does not mean multiplication the way * does. It requires the operands to implement the corresponding matrix multiplication protocol.

For example, using NumPy:

import numpy as np

A = np.array([
    [1, 2],
    [3, 4]
])

B = np.array([
    [5, 6],
    [7, 8]
])

C = A @ B

print(C)

Result:

[[19 22]
 [43 50]]

Matrix multiplication via * may also be given a different meaning in some libraries, so you need to confirm the operation rules according to the specific type.

The relevant special methods include:

  • __matmul__(): implements @.
  • __rmatmul__(): implements right-hand matrix multiplication.
  • __imatmul__(): implements @=.

13. Operator Precedence and Associativity

When an expression contains multiple operators, Python needs to determine which part is evaluated first.

Operator precedence determines the default order of evaluation among different operators.

Associativity determines how operators of the same precedence are grouped.

1. Common Operator Precedence

The following are listed from highest to lowest:

Precedence Operator or expression Description
Highest (), [], . Parentheses, indexing, attribute access, function calls, etc.
await x Await expression
** Exponentiation
+x, -x, ~x Unary operators
*, @, /, //, % Multiplication, division, matrix multiplication, remainder
+, - Addition and subtraction
<<, >> Shifts
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
in, not in, is, is not, comparison operators Membership, identity, ordering comparisons
not Logical NOT
and Logical AND
or Logical OR
if ... else Conditional expression
lambda Lambda expression
Lowest := Assignment expression

Note: