Mastering Operators and Expressions in Programming | 编程中的运算符与表达式精讲

📚 Mastering Operators and Expressions in Programming | 编程中的运算符与表达式精讲

Operators are the building blocks of any programming language, enabling us to perform calculations, make comparisons, and control the flow of logic. In the Edexcel A-Level Computer Science specification, a deep understanding of operators and how expressions are evaluated is essential for tackling both theoretical questions and practical programming tasks. This article breaks down every category of operator, explores precedence and associativity, and connects these concepts directly to the Python language used in the exam.

运算符是任何编程语言的构建模块,使我们能够进行计算、比较和控制逻辑流程。在爱德思 A-Level 计算机科学规范中,深刻理解运算符以及表达式如何求值是应对理论问题和实际编程任务的关键。本文拆解每一类运算符,探讨优先级与结合性,并将这些概念直接联系到考试中使用的 Python 语言。


1. Arithmetic Operators | 算术运算符

Arithmetic operators handle mathematical calculations. In Python, the core operators are addition (+), subtraction (-), multiplication (*), division (/), floor division (//), modulus (%), and exponentiation (**). Each returns a numeric result, and it’s critical to note the difference between / (always returns a float) and // (truncates toward negative infinity).

算术运算符处理数学计算。在 Python 中,核心运算符包括加号 (+)、减号 (-)、乘号 (*)、除号 (/)、整除 (//)、取模 (%) 和幂运算 (**)。每个都返回一个数值结果,重点要留意 /(始终返回浮点数)与 //(向负无穷截断)之间的区别。

Operator Description Example (Python) Result
+ Addition 5 + 3 8
Subtraction 9 – 4 5
* Multiplication 7 * 2 14
/ Division (float) 10 / 4 2.5
// Floor division 10 // 4 2
% Modulus (remainder) 10 % 4 2
** Exponentiation 2 ** 3 8

Operator precedence means exponentiation is evaluated before multiplication/division, which in turn come before addition/subtraction. Use parentheses to force a specific evaluation order, as 3 + 4 * 2 gives 11, while (3 + 4) * 2 yields 14.

运算符优先级意味着幂运算在乘除之前求值,而乘除又在加减之前。使用圆括号可以强制特定的求值顺序,例如 3 + 4 * 2 结果为 11,而 (3 + 4) * 2 结果为 14。


2. Comparison Operators | 比较运算符

Comparison operators, also called relational operators, evaluate the relationship between two values and always produce a Boolean result (True or False). The typical set includes equal to (==), not equal to (!=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=).

比较运算符,也称关系运算符,用于评估两个值之间的关系,并始终产生布尔结果(True 或 False)。常见的集合包括等于 (==)、不等于 (!=)、大于 (>)、小于 (<)、大于等于 (>=) 和小于等于 (<=)。

x == y   x != y   x > y   x < y   x >= y   x <= y

In Python, chaining comparisons is allowed, such as 1 < x < 10, which evaluates as (1 < x) and (x < 10). This is a feature often tested in trace-table questions. Note that == compares values, not memory addresses; to check identity we use 'is'.

在 Python 中,允许链式比较,例如 1 < x < 10,它等价于 (1 < x) and (x < 10)。这一特性在跟踪表题型中经常被测试。注意 == 比较的是值,而非内存地址;要检查身份需使用 'is'。


3. Logical Operators | 逻辑运算符

Logical operators combine Boolean values or expressions. Python provides three keywords: ‘and’, ‘or’, and ‘not’. They follow short-circuit evaluation: ‘and’ stops if the left operand is False; ‘or’ stops if the left operand is True. This behaviour is crucial for efficient code and for avoiding runtime errors.

逻辑运算符用于组合布尔值或布尔表达式。Python 提供了三个关键字:’and’、’or’ 和 ‘not’。它们遵循短路求值:若左操作数为 False,’and’ 立即停止;若左操作数为 True,’or’ 立即停止。这种行为对于高效代码和避免运行时错误至关重要。

  • and: True if both operands are true
  • or: True if at least one operand is true
  • not: Inverts the Boolean value
  • and:两个操作数都为真时结果为真
  • or:至少一个操作数为真时结果为真
  • not:反转布尔值

Truth tables are a standard way to document logical operators. In Edexcel exams, you may need to simplify complex Boolean expressions using laws like De Morgan’s: not (A and B) is equivalent to (not A) or (not B).

真值表是记录逻辑运算符的标准方式。在爱德思考试中,你可能需要利用德摩根定律等法则化简复杂布尔表达式:not (A and B) 等价于 (not A) or (not B)。


4. Assignment Operators | 赋值运算符

The basic assignment operator (=) stores a value in a variable. Python also offers compound assignment operators that combine an arithmetic or bitwise operation with assignment, such as +=, -=, *=, /=, //=, %=, **=, &=, |=, ^=, <<=, and >>=. These make code more concise and often more readable.

基本赋值运算符 (=) 将一个值存入变量。Python 还提供了复合赋值运算符,它们将算术或位运算与赋值相结合,例如 +=、-=、*=、/=、//=、%=、**=、&=、|=、^=、<<= 和 >>=。这些运算符让代码更简洁,通常也更易读。

x += 5   is equivalent to   x = x + 5

It is important to remember that an assignment is a statement, not an expression. In Python, assignment does not return a value, which differs from languages like C. Therefore, you cannot write if (x = 5): — that would be a syntax error.

务必记住,赋值是一条语句,而非表达式。在 Python 中,赋值不返回值,这与 C 等语言不同。因此,你不能写 if (x = 5): —— 那会是语法错误。


5. Bitwise Operators | 位运算符

Bitwise operators act on integer values at the binary level. They include AND (&), OR (|), XOR (^), NOT (~), left shift (<<), and right shift (>>). These are commonly used in low-level programming, encryption, and efficient mathematical operations.

位运算符在二进制级别对整数值进行操作。它们包括按位与 (&)、按位或 (|)、按位异或 (^)、按位取反 (~)、左移 (<<) 和右移 (>>)。这些通常用于底层编程、加密和高效的数学运算。

For example, 5 & 3 (binary 101 & 011) yields 1 (001). A left shift by 1 (x << 1) multiplies the number by 2, while a right shift (x >> 1) performs integer division by 2, discarding any remainder. These operators appear in topics like binary manipulation and algorithm optimisation.

例如,5 & 3(二进制 101 & 011)结果为 1 (001)。左移 1 位 (x << 1) 相当于将数字乘以 2,而右移 1 位 (x >> 1) 相当于整除 2,舍弃余数。这些运算符出现在二进制操作和算法优化等课题中。


6. String Operators | 字符串运算符

Python treats strings as sequences, allowing the use of the concatenation operator (+) and the repetition operator (*). The expression “Hello” + ” ” + “World” produces “Hello World”, while “Edexcel” * 3 yields “EdexcelEdexcelEdexcel”.

Python 将字符串视为序列,允许使用拼接运算符 (+) 和重复运算符 (*)。表达式 “Hello” + ” ” + “World” 产生 “Hello World”,而 “Edexcel” * 3 会产生 “EdexcelEdexcelEdexcel”。

The ‘in’ and ‘not in’ operators check for the presence of a substring. For instance, ‘ex’ in ‘Edexcel’ returns True. Similarly, comparison operators can be used on strings, comparing them lexicographically based on Unicode code points; thus ‘apple’ < 'banana' is True.

‘in’ 和 ‘not in’ 运算符用于检查子字符串是否存在。例如,’ex’ in ‘Edexcel’ 返回 True。同样,比较运算符也可用于字符串,基于 Unicode 码点按照字典序进行比较;因此 ‘apple’ < 'banana' 为 True。


7. Operator Precedence | 运算符优先级

When multiple operators appear in a single expression, precedence determines the order of evaluation. Python defines a strict hierarchy: exponentiation comes first, followed by unary plus/minus, multiplication/division/floor division/modulus, then addition/subtraction, comparisons, logical NOT, AND, and finally OR.

当一个表达式中出现多个运算符时,优先级决定了求值顺序。Python 定义了严格的层级:幂运算最先,其次是一元加减,接着是乘/除/整除/取模,然后是加减,比较,逻辑 NOT、AND,最后是 OR。

Highest: ** → +x, -x → *, /, //, % → +, – → ==, !=, <, etc. → not → and → or :Lowest

In an expression like 10 – 2 ** 3 + 4 // 2, evaluation unfolds as: 2 ** 3 = 8, then 4 // 2 = 2, then 10 – 8 + 2 = 4. Ambiguity should always be resolved with parentheses for clarity, especially in exam code snippets.

在类似 10 – 2 ** 3 + 4 // 2 的表达式中,求值过程如下:2 ** 3 = 8,然后是 4 // 2 = 2,最后 10 – 8 + 2 = 4。为清晰起见,尤其在考试代码片段中,应始终使用括号消除歧义。


8. Associativity of Operators | 运算符结合性

Associativity decides the direction of evaluation when operators of the same precedence appear consecutively. Most operators in Python are left-associative, meaning they are evaluated from left to right. For example, 100 / 10 / 5 is processed as (100 / 10) / 5, giving 2.0, not 100 / (10 / 5).

结合性决定了相同优先级的运算符连续出现时的求值方向。Python 中大多数运算符是左结合的,意味着它们从左向右求值。例如,100 / 10 / 5 按 (100 / 10) / 5 处理,得到 2.0,而非 100 / (10 / 5)。

The exponentiation operator ** is a notable exception: it is right-associative, so 2 ** 3 ** 2 is evaluated as 2 ** (3 ** 2) = 2 ** 9 = 512, not (2 ** 3) ** 2 = 64. Assignment operators are also right-associative, allowing a = b = c = 0 to assign zero to all three variables.

幂运算符 ** 是一个明显的例外:它是右结合的,因此 2 ** 3 ** 2 按 2 ** (3 ** 2) = 2 ** 9 = 512 求值,而非 (2 ** 3) ** 2 = 64。赋值运算符也是右结合的,允许 a = b = c = 0 将零赋予全部三个变量。


9. Expressions Evaluation | 表达式求值

An expression is any combination of values, variables, operators, and function calls that evaluates to a single value. In trace-table questions, you must be able to step through complex expressions and show the intermediate results. Python follows strict evaluation rules, where sub-expressions are fully evaluated before the next operation.

表达式是值、变量、运算符和函数调用的任意组合,求值后得到一个单一值。在跟踪表题型中,你必须能够逐步分析复杂表达式,并展示中间结果。Python 遵循严格的求值规则,子表达式在下一步操作之前会被完全求值。

Consider the Boolean expression: (age > 18 and citizen == True) or (has_permit == True). Short-circuit rules mean if age > 18 is False, the entire ‘and’ clause returns False without checking citizen. If the first part is False, it then evaluates the right side of ‘or’. Understanding this prevents errors and is a frequent exam focus.

考虑布尔表达式:(age > 18 and citizen == True) or (has_permit == True)。短路规则意味着如果 age > 18 为 False,整个 ‘and’ 子句就直接返回 False,而不会再检查 citizen。如果第一部分为 False,则接着评估 ‘or’ 的右侧。理解这一点能防止错误,也是考试中常见的关注点。


10. Common Mistakes and How to Avoid Them | 常见错误与如何避免

One typical pitfall is confusing the assignment operator (=) with the equality operator (==). In an if statement, writing if x = 5: raises a SyntaxError; the correct form is if x == 5:. Another mistake is misreading operator precedence, such as expecting not x == y to be equivalent to (not x) == y, when it is actually not (x == y).

一个典型的陷阱是混淆赋值运算符 (=) 与相等运算符 (==)。在 if 语句中,写 if x = 5: 会引发 SyntaxError;正确的形式是 if x == 5:。另一个错误是误判运算符优先级,比如期望 not x == y 等价于 (not x) == y,而实际上它等同于 not (x == y)。

When dealing with integer division, students sometimes forget that / always yields a float in Python 3. If an integer result is required, // must be used. Also, chained comparisons can produce unexpected results if not fully understood — a < b == c is not the same as a < b and b == c in all contexts regarding object identity vs equality, but the logical outcome is the same.

处理整数除法时,学生有时会忘记在 Python 3 中 / 始终产生浮点数。若需要整数结果,必须使用 //。此外,链式比较如果未完全理解,可能会产生意想不到的结果——a < b == c 在对象身份与相等性方面并不总是等同于 a < b and b == c,但逻辑结果相同。


11. Exam Tips for Edexcel A-Level | 爱德思 A-Level 考试技巧

In Paper 1 (Principles of Computer Science) and Paper 2 (Application of Computational Thinking), Edexcel frequently includes questions that ask you to complete trace tables, debug code, or predict the output of small programs. A solid grasp of operators and precedence is directly rewarded. Always write intermediate evaluation steps clearly when tracing.

在试卷一(计算机科学原理)和试卷二(计算思维应用)中,爱德思经常包含要求你完成跟踪表、调试代码或预测小程序输出的题目。对运算符和优先级的牢固掌握会直接得分。跟踪时务必清晰地写出中间求值步骤。

When asked to write code, choose compound assignment operators where possible to show modern Python style. Always comment on any non-obvious expression, especially those relying on short-circuit behaviour. For theory questions, be ready to construct truth tables and explain how bitwise manipulation can be used for tasks like checking odd/even (x & 1) or fast multiplication/division.

当被要求编写代码时,尽可能选择复合赋值运算符,以展示现代 Python 风格。对于任何不直观的表达式,尤其是依赖短路行为的,务必添加注释。对于理论题,要做好构建真值表的准备,并能解释如何利用位操作来执行诸如检查奇偶性 (x & 1) 或快速乘除等任务。


12. Summary | 总结

Operators and expressions form the grammar of programming. By mastering arithmetic, comparison, logical, assignment, bitwise, and string operators, and by internalising precedence and associativity rules, you equip yourself to read and write complex code with confidence. Regular practice with trace tables and exam-style problems will turn this knowledge into clear marks on your Edexcel A-Level Computer Science papers.

运算符和表达式构成了编程的语法。通过掌握算术、比较、逻辑、赋值、位和字符串运算符,并内化优先级和结合性规则,你将能够自信地阅读和编写复杂代码。定期使用跟踪表和考试风格的问题进行练习,会将这一知识转化为爱德思 A-Level 计算机科学试卷上清晰的分数。

Published by TutorHao | Computer Science Revision Series | aleveler.com

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

Comments

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

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

Exit mobile version