Operators and Precedence in Programming | 编程中的运算符与优先级

📚 Operators and Precedence in Programming | 编程中的运算符与优先级

Operators are the building blocks of any programming language, enabling you to perform calculations, compare values, and control the flow of logic. In A-Level Edexcel Computer Science, a solid grasp of arithmetic, relational, logical, and combined assignment operators — along with their precedence — is essential for writing correct and efficient code. Understanding the exact order in which operators are evaluated helps you avoid subtle bugs and tackle exam questions with confidence.

运算符是任何编程语言的构建基石,它们使你能执行计算、比较值并控制逻辑流程。在A-Level Edexcel计算机科学课程中,牢固掌握算术、关系、逻辑及复合赋值运算符,以及它们的优先级,对于编写正确且高效的代码至关重要。理解运算符的求值顺序能帮助你避免细微的错误,并自信地应对考试题目。


1. What are Operators? | 什么是运算符?

An operator is a symbol that tells the compiler or interpreter to perform a specific mathematical, relational, or logical operation. Operators act on operands — the values or variables they operate on. For example, in the expression a + b, ‘+’ is the operator, and ‘a’ and ‘b’ are the operands.

运算符是一种符号,它告诉编译器或解释器执行特定的数学、关系或逻辑运算。运算符作用于操作数——即它们所操作的值或变量。例如,在表达式 a + b 中,“+”是运算符,而“a”和“b”是操作数。

Programming languages typically classify operators into several categories: arithmetic, relational (comparison), logical, bitwise, assignment, and more. The Edexcel specification focuses on the first four groups, with particular emphasis on how they interact in compound expressions.

编程语言通常将运算符分为几类:算术、关系(比较)、逻辑、位、赋值等。Edexcel 考试大纲的重点在于前四类,尤其关注它们在复合表达式中的相互作用。


2. Arithmetic Operators | 算术运算符

Arithmetic operators perform standard mathematical calculations. In most languages, including Python and pseudocode used in Edexcel papers, the core arithmetic operators are:

  • + (addition)
  • (subtraction)
  • * (multiplication)
  • / (division: returns a float in Python, but can be integer division in some contexts)
  • // (integer division, discarding remainder)
  • % (modulus: remainder of division)
  • ** (exponentiation)

算术运算符执行标准的数学计算。在包括 Python 及 Edexcel 试卷中伪代码在内的大多数语言中,核心算术运算符有:

  • +(加法)
  • (减法)
  • *(乘法)
  • /(除法:Python 中返回浮点数,但在某些上下文中可能是整数除法)
  • //(整除,舍弃余数)
  • %(取模:除法的余数)
  • **(乘方)

Note that the division operator ‘/’ can cause confusion: in Python, 5 / 2 yields 2.5, whereas integer division ‘//’ gives 2. The modulus operator is frequently used to check divisibility or wrap around arrays.

请注意除法运算符“/”可能引起混淆:在 Python 中,5 / 2 得到 2.5,而整除“//”则得到 2。取模运算符经常用于检查整除性或实现数组的循环。


3. Relational (Comparison) Operators | 关系(比较)运算符

Relational operators compare two values and return a Boolean result (True or False). These are vital for decision-making structures like if statements and loops. The standard set includes:

  • == (equal to)
  • != or <> (not equal to; Python uses !=)
  • > (greater than)
  • < (less than)
  • >= (greater than or equal to)
  • <= (less than or equal to)

关系运算符比较两个值并返回布尔值(TrueFalse)。它们对于 if 语句和循环等决策结构至关重要。标准集合包括:

  • ==(等于)
  • !=<>(不等于;Python 使用 !=)
  • >(大于)
  • <(小于)
  • >=(大于或等于)
  • <=(小于或等于)

Be careful not to confuse the equality operator ‘==’ with the assignment operator ‘=’. A common beginner mistake is writing if x = 5: instead of if x == 5:, which leads to a syntax error in Python.

注意不要将相等运算符“==”与赋值运算符“=”混淆。一个常见的初学者错误是写成 if x = 5: 而非 if x == 5:,这在 Python 中会导致语法错误。


4. Logical Operators | 逻辑运算符

Logical operators combine or modify Boolean expressions. The three primary logical operators are AND, OR, and NOT. In many languages, including Python, these are written as and, or, and not. They follow truth tables that define the output for every combination of inputs.

逻辑运算符用于组合或修改布尔表达式。三个主要的逻辑运算符是 ANDORNOT。在包括 Python 在内的许多语言中,它们写作 andornot。它们遵循真值表,为每种输入组合定义了输出。

Example: (age >= 18) and (hasLicense == True) evaluates to True only if both conditions hold. The not operator inverts a Boolean: not(isRaining) is True when isRaining is False.

示例:(age >= 18) and (hasLicense == True) 仅当两个条件均为真时才为 True。not 运算符反转布尔值:当 isRaining 为 False 时,not(isRaining) 为 True。

Logical operators are often short-circuit evaluated: in an and expression, if the left operand is False, the right operand is never evaluated because the result is already determined. This can be exploited for efficiency or to avoid errors (e.g., checking that a list is non-empty before accessing its first element).

逻辑运算符通常执行短路求值:在 and 表达式中,如果左操作数为 False,就不再计算右操作数,因为结果已经确定为 False。这可用于提高效率或避免错误(例如,在访问列表第一个元素前先检查列表非空)。


5. Bitwise Operators | 位运算符

Although less frequently highlighted in introductory A-Level topics, bitwise operators manipulate individual bits within an integer. They include & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), and >> (right shift). Edexcel may include them in questions on low-level data manipulation or binary flags.

虽然位运算符在 A-Level 入门主题中不常见,它们用于操作整数中的单个位。包括 &(与)、|(或)、^(异或)、~(非)、<<(左移)和 >>(右移)。Edexcel 可能在低层数据操作或二进制标志的题目中涉及它们。

For example, to test if the third bit (from the right) is set, you can use if (number & 0b100) != 0:. Shifts are equivalent to multiplying or dividing by powers of two: x << 3 is the same as x * 8.

例如,要测试右数第三位是否为 1,可以使用 if (number & 0b100) != 0:。移位等同于乘以或除以 2 的幂:x << 3 与 x * 8 相同。


6. Assignment and Combined Assignment Operators | 赋值与复合赋值运算符

The basic assignment operator = stores a value in a variable. Combined assignment operators provide a shorthand for updating a variable based on its current value. They have the general form operand1 op= operand2, which is equivalent to operand1 = operand1 op operand2.

基本赋值运算符 = 将一个值存入变量中。复合赋值运算符提供了一种简写方式,用于基于变量的当前值更新该变量。它们的一般形式为 操作数1 op= 操作数2,等价于 操作数1 = 操作数1 op 操作数2

Common combined operators include +=, -=, *=, /=, %=, //=, and **=. For instance, count += 1 increments count by 1. These operators are not only convenient but can also make code more readable and slightly more efficient.

常见的复合运算符有 +=-=*=/=%=//=**=。例如,count += 1 将 count 增加 1。这些运算符不仅方便,还能让代码更易读,并且略微提高效率。

It is important to understand that the combined assignment is a single operation: in x += y, x is updated in place if mutable; for immutable types (like integers), a new object is created and assigned back to x.

理解复合赋值是单一操作这一点很重要:在 x += y 中,如果 x 是可变的,则就地更新;对于不可变类型(如整数),则会创建一个新对象并赋回给 x。


7. Operator Precedence | 运算符优先级

Operator precedence defines the order in which different operators are evaluated when an expression contains multiple operators. Without a clear precedence, expressions like 3 + 4 * 2 would be ambiguous: does it equal (3+4)*2=14 or 3+(4*2)=11? Precedence rules resolve this by giving multiplication higher priority than addition, so the correct result is 11.

运算符优先级定义了当表达式包含多个运算符时,不同运算符的求值顺序。若无明确的优先级,类似 3 + 4 * 2 的表达式将产生歧义:它等于 (3+4)*2=14 还是 3+(4*2)=11?优先级规则通过赋予乘法高于加法的优先级解决了这一问题,因此正确结果是 11。

In languages like Python and most pseudocode used by Edexcel, the precedence hierarchy (from highest to lowest) is roughly:

Precedence Level Operator Group Examples
1 (highest) Parentheses ( )
2 Exponentiation **
3 Unary plus/minus, logical NOT, bitwise NOT +x, -x, not x, ~x
4 Multiplication, Division, Modulus, Integer Division * / % //
5 Addition, Subtraction + –
6 Bitwise shifts << >>
7 Relational (comparison) < <= > >= == !=
8 Bitwise AND, XOR, OR & ^ |
9 Logical AND and
10 (lowest) Logical OR or

This table is based on Python, which is the primary language studied.

在 Python 及 Edexcel 使用的大多数伪代码中,优先级层次(从高到低)大致如下:

优先级 运算符类别 示例
1(最高) 括号 ( )
2 乘方 **
3 一元加/减、逻辑非、位非 +x, -x, not x, ~x
4 乘、除、取模、整除 * / % //
5 加、减 + –
6 位移 << >>
7 关系(比较) < <= > >= == !=
8 位与、异或、或 & ^ |
9 逻辑与 and
10(最低) 逻辑或 or

此表以 Python 为基础,这也是学习的主要语言。


8. Precedence Rules in Detail | 优先级规则详解

When operators have the same precedence, evaluation proceeds from left to right according to associativity rules (discussed next). However, some operators are right-associative, like exponentiation **. For example, 2 ** 3 ** 2 is evaluated as 2 ** (3 ** 2) = 2 ** 9 = 512, not (2 ** 3) ** 2 = 64.

当运算符具有相同的优先级时,将根据结合性规则(接下来讨论)从左向右进行求值。但有些运算符是右结合的,比如乘方 **。例如,2 ** 3 ** 2 被求值为 2 ** (3 ** 2) = 2 ** 9 = 512,而不是 (2 ** 3) ** 2 = 64。

In the Edexcel exam, you might be asked to predict the result of an expression like 5 + 2 * 3 ** 2 – 4 // 2. Step-by-step evaluation according to precedence:

  • Exponentiation: 3 ** 2 = 9
  • Multiplication: 2 * 9 = 18
  • Integer division: 4 // 2 = 2
  • Addition and subtraction (left to right): 5 + 18 = 23; 23 – 2 = 21

Thus the result is 21.

在 Edexcel 考试中,你可能会被要求预测如 5 + 2 * 3 ** 2 – 4 // 2 这样的表达式的结果。根据优先级逐步求值:

  • 乘方:3 ** 2 = 9
  • 乘法:2 * 9 = 18
  • 整除:4 // 2 = 2
  • 加法和减法(从左向右):5 + 18 = 23;23 – 2 = 21

因此结果为 21。

Practice with parentheses can help you verify: writing (5 + (2 * (3 ** 2)) – (4 // 2)) makes the precedence explicit.

使用括号进行练习可以帮助你验证:写成 (5 + (2 * (3 ** 2)) – (4 // 2)) 可以使优先级明确。


9. Associativity | 结合性

Associativity determines the direction of evaluation when two operators of the same precedence appear in an expression. Most arithmetic operators are left-associative, meaning operations are grouped from the left. For example, 10 – 4 – 2 is interpreted as (10 – 4) – 2 = 4, not 10 – (4 – 2) = 8.

结合性决定了当表达式中出现两个相同优先级的运算符时的求值方向。大多数算术运算符是左结合的,即从左开始分组。例如,10 – 4 – 2 被解释为 (10 – 4) – 2 = 4,而不是 10 – (4 – 2) = 8。

Right-associative operators include exponentiation ** and assignment = (and combined assignments). For assignment, a = b = 5 is equivalent to a = (b = 5), assigning 5 to b and then to a. Python’s ** is right-associative, but note that unary minus binds differently; -2 ** 3 is -(2 ** 3) = -8 because exponentiation has higher precedence than unary minus.

右结合运算符包括乘方 ** 和赋值 =(以及复合赋值)。对于赋值,a = b = 5 等价于 a = (b = 5),先将 5 赋给 b,再赋给 a。Python 的 ** 是右结合的,但请注意一元减号绑定方式不同;-2 ** 3 是 -(2 ** 3) = -8,因为乘方的优先级高于一元减号。


10. Using Parentheses to Control Evaluation | 使用括号控制求值顺序

Parentheses override the default precedence and associativity, forcing the enclosed subexpression to be evaluated first. When in doubt about the order, use parentheses to make the intent explicit — it improves code readability and prevents logic errors. For instance, (a + b) * c guarantees addition before multiplication.

括号可以覆盖默认的优先级和结合性,强制先计算括号内的子表达式。当对顺序不确定时,使用括号明确表达意图——这能提高代码可读性并防止逻辑错误。例如,(a + b) * c 确保加法在乘法之前进行。

In complex Boolean expressions, parentheses are invaluable: (age >= 65) or ( (age <= 18) and (hasParentalConsent) ) clarifies the logic without relying on the reader knowing that ‘and’ binds tighter than ‘or’.

在复杂的布尔表达式中,括号非常有用:(age >= 65) or ( (age <= 18) and (hasParentalConsent) ) 清晰地展示了逻辑,而不需要读者知道“and”比“or”结合得更紧。


11. Common Mistakes and Debugging | 常见错误与调试

One frequent pitfall is confusing assignment ‘=’ with equality ‘==’. Another is forgetting that integer division ‘//’ truncates toward negative infinity in Python, so -7 // 2 yields -4, not -3. A common precedence mistake is writing not a == b when you mean not (a == b); the expression not a == b is actually parsed as (not a) == b because ‘not’ has higher precedence than ‘==’, leading to unexpected results.

一个常见的陷阱是将赋值“=”与相等“==”混淆。另一个是忘记 Python 中整除“//”向负无穷方向截断,因此 -7 // 2 结果是 -4,而不是 -3。一个典型的优先级错误是本想表达 not (a == b) 却写成了 not a == b;实际上 not a == b 被解析为 (not a) == b,因为“not”优先级高于“==”,导致意外结果。

Debugging such issues often involves inserting temporary print statements or using a step-by-step evaluator. Remember: when in doubt, add parentheses. Edexcel examiners love to test these subtle precedence corners.

调试此类问题通常需要插入临时的打印语句或使用逐步求值器。记住:当不确定时,请添加括号。Edexcel 考官喜欢考察这些细微的优先级陷阱。


12. Exam-style Questions and Tips | 考试风格问题与技巧

Typical Edexcel questions will present a short piece of code containing multiple operators and ask you to state the output or the final value of a variable. You may also be asked to draw an expression tree or explain the evaluation order. Always break the expression down into its constituents based on the precedence table, handling the highest-precedence operations first.

典型的 Edexcel 题目会给出包含多个运算符的一小段代码,要求你陈述输出或变量的最终值。你也可能被要求画出表达式树或解释求值顺序。务必根据优先级表格将表达式分解为各个组成部分,优先处理最高优先级的运算。

When combining logical and comparison operators, evaluate comparisons first, then ‘not’, then ‘and’, finally ‘or’. For example:

result = 5 > 3 and 2 + 2 == 4 or not 7 < 5

Evaluate: 5>3 → True, 2+2 → 4, 4==4 → True, not 7<5 → not False → True. Then: True and True → True, True or True → True.

当组合逻辑运算符和比较运算符时,先计算比较,然后是“not”,再是“and”,最后是“or”。例如:

result = 5 > 3 and 2 + 2 == 4 or not 7 < 5

求值:5>3 → True,2+2 → 4,4==4 → True,not 7<5 → not False → True。然后:True and True → True,True or True → True。

Practice by writing your own nested expressions and checking their values in a Python interpreter. This builds confidence for the exam while reinforcing your understanding of both syntax and precedence.

通过编写自己的嵌套表达式并在 Python 解释器中检查其值来进行练习。这既能建立考试信心,又能巩固你对语法和优先级的理解。


Published by TutorHao | Programming Revision Series | aleveler.com

更多咨询请联系16621398022(同微信)

Comments

屏轩国际教育cambridge primary/secondary checkpoint, cat4, ukiset,ukcat,igcse,alevel,PAT,STEP,MAT, ibdp,ap,ssat,sat,sat2课程辅导,国外大学本科硕士研究生博士课程论文辅导

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from aleveler.com

Subscribe now to keep reading and get access to the full archive.

Continue reading