Operators and Expressions in Python | Python 中的运算符与表达式

📚 Operators and Expressions in Python | Python 中的运算符与表达式

In A-Level Computer Science, a solid understanding of operators and expressions is essential for constructing correct algorithms and writing efficient code. This article explores the full range of operators available in Python, from basic arithmetic to bitwise manipulation, and explains how expressions are evaluated according to precedence and associativity rules.

在A-Level计算机科学中,深入理解运算符和表达式对于构建正确算法和编写高效代码至关重要。本文将全面探讨Python中可用的各种运算符——从基本算术到位运算,并解释表达式如何根据优先级和结合性规则进行求值。

1. Arithmetic Operators | 算术运算符

Arithmetic operators perform mathematical calculations on numeric operands. The basic ones include addition (+), subtraction (-), multiplication (*), and division (/). Python also provides floor division (//), modulus (%), and exponentiation (**).

算术运算符对数值操作数执行数学计算。基本运算符包括加法(+)、减法(-)、乘法(*)和除法(/)。Python还提供整除(//)、取模(%)和幂运算(**)。

When using division (/), the result is always a float, even if both operands are integers. For example, 7 / 2 yields 3.5. Floor division (//) discards the fractional part and returns an integer when both operands are integers: 7 // 2 gives 3.

使用除法(/)时,即使两个操作数都是整数,结果也总是浮点数。例如,7 / 2 得出 3.5。整除(//)会丢弃小数部分,当两个操作数都为整数时返回整数:7 // 2 得到 3

The modulus operator (%) returns the remainder of a division: 7 % 2 evaluates to 1. Exponentiation (**) raises the left operand to the power of the right operand: 2 ** 3 equals 8. Negative exponents produce fractional results, so 2 ** -1 is 0.5.

取模运算符(%)返回除法的余数:7 % 2 求值结果为 1。幂运算(**)将左操作数提升到右操作数的幂:2 ** 3 等于 8。负指数产生小数结果,因此 2 ** -10.5


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

Comparison operators compare two values and return a Boolean result (True or False). The operators are: equal to (==), not equal to (!=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=).

比较运算符比较两个值并返回布尔结果(TrueFalse)。这些运算符是:等于(==)、不等于(!=)、大于(>)、小于(<)、大于等于(>=)和小于等于(<=)。

These operators work with numbers, strings, and other comparable types. For strings, comparison is based on lexicographical order using Unicode values. Thus, 'apple' < 'banana' is True, while 'Apple' < 'apple' depends on the uppercase letter's lower code point.

这些运算符适用于数字、字符串和其他可比较类型。对于字符串,比较基于Unicode值的字典顺序。因此,'apple' < 'banana'True,而 'Apple' < 'apple' 取决于大写字母较小的码点。

Chained comparisons are allowed in Python, so 1 < x < 10 checks whether x is between 1 and 10 exclusively. This is equivalent to 1 < x and x < 10 but evaluated only once per operand.

Python允许链式比较,因此 1 < x < 10 检查 x 是否严格介于1和10之间。这等价于 1 < x and x < 10,但每个操作数只求值一次。


3. Assignment Operators | 赋值运算符

Assignment operators are used to assign values to variables. The basic assignment operator is =. Compound assignment operators combine an arithmetic or bitwise operation with assignment, such as +=, -=, *=, /=, //=, %=, **=, &=, |=, ^=, <<=, and >>=.

赋值运算符用于将值赋给变量。基本赋值运算符是 =。复合赋值运算符将算术或位运算与赋值组合在一起,例如 +=、-=、*=、/=、//=、%=、**=、&=、|=、^=、<<= 和 >>=。

For instance, x += 5 is a shorthand for x = x + 5. These operators modify the variable in place when possible (e.g., for mutable objects), but for immutable types like integers, a new object is created and rebound.

例如,x += 5x = x + 5 的简写。这些运算符在可能的情况下会原地修改变量(例如对可变对象),但对于整数等不可变类型,会创建一个新对象并重新绑定。

Python also supports multiple assignments in one statement: a, b = 10, 20 swaps values efficiently with a, b = b, a without needing a temporary variable.

Python还支持一条语句中的多重赋值:a, b = 10, 20,并且可以通过 a, b = b, a 高效地交换值,无需临时变量。


4. Logical Operators | 逻辑运算符

Logical operators combine Boolean expressions and return Boolean values. Python provides three: and, or, and not. The truth value of an expression follows standard Boolean logic, with and requiring both operands to be true, or requiring at least one, and not inverting the truth value.

逻辑运算符组合布尔表达式并返回布尔值。Python提供三个:andornot。表达式的真值遵循标准布尔逻辑,and 要求两个操作数都为真,or 要求至少一个为真,not 颠倒真值。

These operators are short-circuit evaluated: a and b does not evaluate b if a is false, and a or b does not evaluate b if a is true. This can be exploited to avoid errors, such as checking that a variable is not None before accessing its attribute.

这些运算符采用短路求值:如果 a 为假,a and b 不会对 b 求值;如果 a 为真,a or b 不会对 b 求值。可以利用这一点避免错误,例如在访问变量属性之前先检查它不为 None

In Python, any non-zero number or non-empty object is considered true in a Boolean context. Hence, 4 and 5 returns 5, not just True, because the expression returns the last evaluated operand.

在Python中,任何非零数字或非空对象在布尔上下文中都被视为真。因此,4 and 5 返回 5,而不仅仅是 True,因为表达式返回的是最后求值的操作数。


5. Bitwise Operators | 位运算符

Bitwise operators treat operands as sequences of binary digits and operate on each bit individually. The operators are: & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), and >> (right shift).

位运算符将操作数视为二进制数字序列,并对每个位单独操作。运算符包括:&(与)、|(或)、^(异或)、~(非)、<<(左移)和 >>(右移)。

For example, 5 & 3 performs bitwise AND on binary 101 and 011, resulting in 001, which is 1. The bitwise NOT operator (~) inverts all bits using two's complement representation: ~5 yields -6 because the sign bit and magnitude change.

例如,5 & 3 对二进制101和011执行按位与操作,得到001,即1。按位非运算符(~)使用二进制补码表示反转所有位:~5 得到 -6,因为符号位和数值都发生了变化。

Shift operators move bits left or right by a specified number of positions. Left shift (n << k) multiplies n by 2k, while right shift (n >> k) performs floor division by 2k for non-negative numbers. For negative numbers, right shift fills with the sign bit in Python, preserving the sign.

移位运算符将位向左或向右移动指定的位数。左移(n << k)相当于 n 乘以 2k,而右移(n >> k)对于非负数执行除以 2k 的整除。对于负数,Python中右移会用符号位填充,保留符号。

Bitwise operators are commonly used in low-level programming, flag manipulation, and optimization of certain arithmetic operations.

位运算符通常用于底层编程、标志操纵以及某些算术操作的优化。


6. Membership and Identity Operators | 成员和身份运算符

Membership operators test whether a value is present in a sequence (string, list, tuple, etc.). The operators are in and not in. For example, 'a' in 'apple' returns True, and 5 not in [1,2,3] returns True.

成员运算符检查一个值是否存在于序列(字符串、列表、元组等)中。运算符有 innot in。例如,'a' in 'apple' 返回 True5 not in [1,2,3] 返回 True

Identity operators compare the memory locations of two objects: is and is not. They differ from equality (==) because two objects with the same value may not necessarily be the same object. For instance, a = [1,2]; b = [1,2]; a is b returns False while a == b is True.

身份运算符比较两个对象的内存位置:isis not。它们与相等(==)不同,因为值相同的两个对象未必是同一个对象。例如,a = [1,2]; b = [1,2]; a is b 返回 False,而 a == bTrue

However, Python caches small integers and interned strings, so a = 256; b = 256; a is b may be True, but this is an implementation detail and should not be relied upon for correctness.

然而,Python会缓存小整数和驻留字符串,因此 a = 256; b = 256; a is b 可能为 True,但这属于实现细节,不应依赖它来确保正确性。


7. Operator Precedence | 运算符优先级

Operator precedence determines the order in which operations are performed in an expression lacking explicit parentheses. In Python, exponentiation has the highest precedence, followed by unary operators, then multiplication/division, then addition/subtraction, then bitwise shifts, then bitwise AND, XOR, OR, and finally comparisons and logical operators.

运算符优先级决定了在没有显式括号的表达式中执行操作的顺序。在Python中,幂运算的优先级最高,其次是一元运算符,然后是乘除、加减、移位、位与、异或、位或,最后是比较和逻辑运算符。

The acronym PEMDAS is partially applicable, but bitwise and logical operators extend the rule. A full precedence table is as follows:

助记词 PEMDAS 部分适用,但位运算和逻辑运算扩展了该规则。完整的优先级表如下:

Operator Description 中文描述
** Exponentiation 幂运算
+x, -x, ~x Unary plus, minus, bitwise NOT 一元加、减、按位非
*, /, //, % Multiplication, division, floor division, modulus 乘、除、整除、取模
+, - Addition and subtraction 加法和减法
<<, >> Bitwise shifts 位移
& Bitwise AND 按位与
^ Bitwise XOR 按位异或
| Bitwise OR 按位或
==, !=, >, <, >=, <=, is, is not, in, not in Comparisons, identity, membership 比较、身份、成员
not Logical NOT 逻辑非
and Logical AND 逻辑与
or Logical OR 逻辑或

When operators share the same precedence, evaluation proceeds according to associativity. Most operators are left-associative, meaning they group left-to-right. The exponentiation operator ** is right-associative, so 2 ** 3 ** 2 is evaluated as 2 ** (3 ** 2), i.e., 2 ** 9 = 512.

当运算符具有相同优先级时,按照结合性进行求值。大多数运算符是左结合的,即从左到右分组。幂运算符 ** 是右结合的,因此 2 ** 3 ** 2 被求值为 2 ** (3 ** 2),即 2 ** 9 = 512。

Using parentheses is recommended to avoid ambiguity and improve readability, especially in complex expressions typical of A-Level exam questions.

建议使用括号以避免歧义并提高可读性,尤其是在A-Level考试题中常见的复杂表达式中。


8. Expression Evaluation and Type Coercion | 表达式求值与类型强制转换

An expression is a combination of values, variables, operators, and function calls that the interpreter evaluates to produce a new value. Python evaluates expressions from the innermost parentheses outward, applying operator precedence and associativity.

表达式是值、变量、运算符和函数调用的组合,解释器对其进行求值以产生新值。Python从最内层括号向外求值,应用运算符优先级和结合性。

Type coercion (implicit conversion) occurs when an operator has operands of different types. For example, adding an integer and a float results in a float: 3 + 4.5 gives 7.5. However, explicit conversion using functions like int(), float(), or str() is often safer and required to avoid TypeError.

当运算符的操作数类型不同时,会发生类型强制转换(隐式转换)。例如,整数与浮点数相加得到浮点数:3 + 4.5 得到 7.5。然而,使用 int()float()str() 等函数进行显式转换通常更安全,并且是避免 TypeError 所必需的。

In Boolean contexts, objects have truth values: empty sequences, zero numbers, None, and False are considered false; all else true. This allows concise conditional statements like if my_list: instead of if len(my_list) > 0:.

在布尔上下文中,对象具有真值:空序列、零数值、NoneFalse 被视为假,其他均为真。这允许使用简洁的条件语句,如 if my_list: 代替 if len(my_list) > 0:


9. Short-Circuit Evaluation | 短路求值

Short-circuit evaluation is a strategy where the second argument of a Boolean operator is executed or evaluated only if the first argument does not suffice to determine the value of the expression. In Python, and and or operators employ this technique.

短路求值是一种策略,只有当第一个参数不足以确定整个表达式的值时,才会执行或求值第二个参数。在Python中,andor 运算符采用了这一技术。

For a and b, if a is false, b is never evaluated because the whole expression must be false. For a or b, if a is true, b is skipped. This not only improves performance but also permits guarding statements: e.g., x is not None and x.value > 5 avoids an AttributeError.

对于 a and b,如果 a 为假,则永远不会对 b 求值,因为整个表达式必然为假。对于 a or b,如果 a 为真,则跳过 b。这不仅提高了性能,还允许保护性语句:例如,x is not None and x.value > 5 可避免 AttributeError

However, short-circuiting can lead to subtle bugs if the right operand has side effects that are expected to execute unconditionally. Therefore, care is needed when combining function calls with logical operators.

然而,如果期望无条件执行右操作数的副作用,短路求值可能导致隐蔽的错误。因此,将函数调用与逻辑运算符合并时需格外小心。


10. Common Pitfalls and Best Practices | 常见陷阱与最佳实践

A common mistake is confusing the assignment operator (=) with the equality operator (==). Writing if x = 5: causes a syntax error in Python, but in some exam pseudocode it might be allowed; be precise. Always use == for comparisons.

一个常见错误是混淆赋值运算符(=)和相等运算符(==)。在Python中写 if x = 5: 会导致语法错误,但在某些考试伪代码中可能允许;务必精确。比较时始终使用 ==。

Another pitfall is chaining assignments incorrectly. The statement a = b = 0 is valid and assigns 0 to both a and b, but a = b == 0 evaluates whether b equals 0 and assigns the Boolean result to a. Use parentheses for clarity: a = (b == 0).

另一个陷阱是错误地链式赋值。语句 a = b = 0 是有效的,并将 0 赋给 a 和 b,但 a = b == 0 会判断 b 是否等于 0,然后将布尔结果赋给 a。为了清晰,请使用括号:a = (b == 0)

Bitwise operators should not be confused with logical ones. & and and serve different purposes. Using & in place of and may not yield a Boolean result and can cause unexpected behavior due to different precedence levels.

位运算符不应与逻辑运算符混淆。&and 用途不同。用 & 代替 and 可能不会产生布尔结果,并且由于优先级不同可能导致意外行为。

Finally, when dealing with floating-point arithmetic, be aware of rounding errors. For example, 0.1 + 0.2 == 0.3 returns False due to binary representation limitations. In such cases, use a tolerance or the decimal module for precise calculations.

最后,处理浮点运算时,要注意舍入误差。例如,0.1 + 0.2 == 0.3 返回 False,这是因为二进制表示的局限性。在这种情况下,可设置容差或使用 decimal 模块进行精确计算。

To master operators for A-Level Edexcel, practice combining operators in complex expressions and always test boundary cases. Thorough understanding will help in both exam questions and programming coursework.

为了掌握A-Level Edexcel的运算符,要练习在复杂表达式中组合使用各种运算符,并始终测试边界情况。透彻的理解将有助于考试题和编程课程作业。

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