Python3 Operators
What is an operator?
This chapter mainly explains Python's operators.
Let's take a simple example:
4 + 5 = 9
In the example,4and5is calledoperand,+calledoperator。
Python language supports the following types of operators:
- Arithmetic operators
- Comparison (relational) operators
- Assignment operators
- Logical operators
- Bitwise operators
- Membership operators
- Identity operators
- Operator precedence
Next, let's learn Python's operators one by one.
Python Arithmetic Operators
The following assumes variablea=10, variableb=21:
| Operator | Description | Example |
|---|---|---|
| + | Addition - Adds two objects | a + b outputs 31 |
| - | Subtraction - Gives a negative number or subtracts one number from another | a - b outputs -11 |
| * | Multiplication - Multiplies two numbers or returns a string repeated a certain number of times | a * b outputs 210 |
| / | Division - x divided by y | b / a outputs 2.1 |
| % | Modulus - Returns the remainder of division | b % a outputs 1 |
| ** | Exponent - Returns x to the power of y | a**b is 10 to the 21st power |
| // | Floor division - Rounds down to the nearest integer |
>>> 9//2 4 >>> -9//2 -5 |
The following example demonstrates the operation of all arithmetic operators in Python:
Example (Python 3.0+)
The above example outputs:
1 - c 的值为: 31 2 - c 的值为: 11 3 - c 的值为: 210 4 - c 的值为: 2.1 5 - c 的值为: 1 6 - c 的值为: 8 7 - c 的值为: 2
Python Comparison Operators
The following assumes variable a is 10 and variable b is 20:
| Operator | Description | Example |
|---|---|---|
| == | Equal to - Compares whether objects are equal | (a == b) returns False. |
| != | Not equal to - Compares whether two objects are not equal | (a != b) returns True. |
| > | Greater than - Returns whether x is greater than y | (a > b) returns False. |
| < | Less than - Returns whether x is less than y. All comparison operators return 1 for true and 0 for false. These are respectively equivalent to the special variables True and False. Note the capitalization of these variable names. | (a < b) returns True. |
| >= | Greater than or equal to - Returns whether x is greater than or equal to y. | (a >= b) returns False. |
| <= | Less than or equal to - Returns whether x is less than or equal to y. | (a <= b) returns True. |
The following example demonstrates the operation of all comparison operators in Python:
Example (Python 3.0+)
The above example outputs:
1 - a 不等于 b 2 - a 不等于 b 3 - a 大于等于 b 4 - a 大于 b 5 - a 小于等于 b 6 - b 大于等于 a
Python Assignment Operators
The following assumes variable a is 10 and variable b is 20:
| Operator | Description | Example |
|---|---|---|
| = | Simple assignment operator | c = a + b assigns the result of a + b to c |
| += | Addition assignment operator | c += a is equivalent to c = c + a |
| -= | Subtraction assignment operator | c -= a is equivalent to c = c - a |
| *= | Multiplication assignment operator | c *= a is equivalent to c = c * a |
| /= | Division assignment operator | c /= a is equivalent to c = c / a |
| %= | Modulus assignment operator | c %= a is equivalent to c = c % a |
| **= | Exponent assignment operator | c **= a is equivalent to c = c ** a |
| //= | Floor division assignment operator | c //= a is equivalent to c = c // a |
| := | Walrus operator, its main purpose is to perform assignment and return the assigned value simultaneously within an expression.New operator added in Python 3.8。 | In this example, the assignment expression avoids calling len() twice: if (n := len(a)) > 10:
print(f"List is too long ({n} elements, expected <= 10)")
|
The following example demonstrates the operation of all assignment operators in Python:
Example (Python 3.0+)
The above example outputs:
1 - c 的值为: 31 2 - c 的值为: 52 3 - c 的值为: 1092 4 - c 的值为: 52.0 5 - c 的值为: 2 6 - c 的值为: 2097152 7 - c 的值为: 99864
In Python 3.8 and later, a new syntax feature called the "Walrus Operator" was introduced, which uses:=symbol. The main purpose of this operator is to perform assignment and return the assigned value simultaneously within an expression.
Using the walrus operator can simplify code in some cases, especially when you need to use the assignment result within an expression. This is useful for simplifying loop conditions or repeated calculations in expressions.
The following is a simple example demonstrating the use of the walrus operator:
Example
n = 10
if n > 5:
print(n)
# Using the walrus operator
if (n := 10) > 5:
print(n)
if (n := 10) > 5:: This is using the walrus operator (:=) syntax. The walrus operator performs an assignment operation within an expression.(n := 10): Assigns the variablento 10 and returns the assignment result at the same time.> 5: Checks whether the assignednis greater than 5. If the condition is true, execute the following code block.
print(n): If the condition is true, print the variablen's value (i.e., 10).
Advantages of the walrus operator:
- The walrus operator (
:=) allows assignment within an expression, which can reduce code duplication and improve code readability and conciseness. - In the above example, the traditional approach requires a separate line to assign
n, and thenifstatement for condition checking. With the walrus operator, the code canifdirectly perform assignment and condition checking within the statement.
Python Bitwise Operators
Bitwise operators treat numbers as binary for calculation. The bitwise operation rules in Python are as follows:
In the table below, variable a is 60 and b is 13. The binary formats are as follows:
a = 0011 1100 b = 0000 1101 ----------------- a&b = 0000 1100 a|b = 0011 1101 a^b = 0011 0001 ~a = 1100 0011
| Operator | Description | Example |
|---|---|---|
| & | Bitwise AND operator: For the two values involved in the operation, if both corresponding bits are 1, the result bit is 1; otherwise, it is 0. | (a & b) outputs 12. Binary explanation: 0000 1100 |
| | | Bitwise OR operator: As long as one of the two corresponding binary bits is 1, the result bit is 1. | (a | b) outputs 61. Binary explanation: 0011 1101 |
| ^ | Bitwise XOR operator: When the two corresponding binary bits are different, the result is 1. | (a ^ b) outputs 49. Binary explanation: 0011 0001 |
| ~ | Bitwise NOT operator: Inverts each binary bit of the data, turning 1 into 0 and 0 into 1.~xsimilar to-x-1 | (~a ) outputs -61. Binary explanation: 1100 0011, in two's complement form for a signed binary number. |
| << | Left shift operator: All binary bits of the operand are shifted left by a specified number of places. The number on the right of "<<" specifies the number of places to shift. High-order bits are discarded, and low-order bits are filled with 0. | a << 2 outputs 240. Binary explanation: 1111 0000 |
| >> | Right shift operator: All binary bits of the operand on the left of ">>" are shifted right by a specified number of places. The number on the right of ">>" specifies the number of places to shift. | a >> 2 outputs 15. Binary explanation: 0000 1111 |
The following examples demonstrate the operations of all Python bitwise operators:
Example (Python 3.0+)
The output of the above example is:
1 - c 的值为: 12 2 - c 的值为: 61 3 - c 的值为: 49 4 - c 的值为: -61 5 - c 的值为: 240 6 - c 的值为: 15
Python Logical Operators
Python language supports logical operators. The following assumes variable a is 10 and b is 20:
| Operator | Logical expression | Description | Example |
|---|---|---|---|
| and | x and y | Boolean AND - If x is False, x and y returns the value of x; otherwise, it returns the evaluated value of y. | (a and b) returns 20. |
| or | x or y | Boolean OR - If x is True, it returns the value of x; otherwise, it returns the evaluated value of y. | (a or b) returns 10. |
| not | not x | Boolean NOT - If x is True, returns False. If x is False, it returns True. | not(a and b) returns False |
The output of the above example is:
Example (Python 3.0+)
The output of the above example is:
1 - 变量 a 和 b 都为 true 2 - 变量 a 和 b 都为 true,或其中一个变量为 true 3 - 变量 a 和 b 有一个不为 true 4 - 变量 a 和 b 都为 true,或其中一个变量为 true 5 - 变量 a 和 b 都为 false,或其中一个变量为 false
Python Membership Operators
In addition to the operators above, Python also supports membership operators. The test instance contains a series of members, including strings, lists, or tuples.
| Operator | Description | Example |
|---|---|---|
| in | Returns True if a value is found in the specified sequence; otherwise, returns False. | x in y sequence: Returns True if x is in the y sequence. |
| not in | Returns True if a value is not found in the specified sequence; otherwise, returns False. | x not in y sequence: Returns True if x is not in the y sequence. |
The following examples demonstrate the operations of all Python membership operators:
Example (Python 3.0+)
The output of the above example is:
1 - 变量 a 不在给定的列表中 list 中 2 - 变量 b 不在给定的列表中 list 中 3 - 变量 a 在给定的列表中 list 中
Python Identity Operators
Identity operators are used to compare the memory locations of two objects.
| Operator | Description | Example |
|---|---|---|
| is | is is used to determine whether two identifiers reference the same object | x is y, similar toid(x) == id(y), if they reference the same object, returns True; otherwise, returns False. |
| is not | is not is used to determine whether two identifiers reference different objects | x is not y, similar toid(x) != id(y). If they do not reference the same object, it returns True; otherwise, it returns False. |
Note: id()The function is used to obtain the memory address of an object.
The following examples demonstrate the operations of all Python identity operators:
Example (Python 3.0+)
The output of the above example is:
1 - a 和 b 有相同的标识 2 - a 和 b 有相同的标识 3 - a 和 b 没有相同的标识 4 - a 和 b 没有相同的标识
The difference between is and ==:
is is used to determine whether two variables reference the same object; == is used to determine whether the values of the referenced variables are equal.
>>>a = [1, 2, 3] >>> b = a >>> b is a True >>> b == a True >>> b = a[:] >>> b is a False >>> b == a True
Python Operator Precedence
The following table lists all operators from highest to lowest precedence. Operators in the same cell have the same precedence. Operators refer to binary operations unless otherwise specified. Operators in the same cell are grouped from left to right (except for exponentiation, which is grouped from right to left):
Operator |
Description |
|---|---|
|
Parenthesized expressions |
|
Subscription, slicing, call, attribute reference |
await x |
await expression |
|
Exponentiation (power) |
|
Positive, negative, bitwise NOT |
|
Multiplication, matrix multiplication, division, floor division, remainder |
|
Addition and subtraction |
|
Shifts |
|
Bitwise AND |
|
Bitwise XOR |
|
Bitwise OR |
|
Comparisons, including membership tests and identity tests |
|
Boolean NOT |
|
Boolean AND |
|
Boolean OR |
|
Conditional expression |
|
lambda expression |
|
Assignment expression |
The following examples demonstrate the operations of all Python operator precedence:
Example (Python 3.0+)
The output of the above example is:
(a + b) * c / d 运算结果为: 90.0 ((a + b) * c) / d 运算结果为: 90.0 (a + b) * (c / d) 运算结果为: 90.0 a + (b * c) / d 运算结果为: 50.0
and has higher precedence:
Example
The above example first evaluatesy and zand returns False, thenx or Falsereturns True, and the output result is:
情况1:默认优先级(先算and) yes 情况2:强制改变优先级(先算or) no
Other extensionsNote:Python3 no longer supports<>operator, you can use!=instead, if you really need to use this comparison operator, you can use the following method:
>>> from __future__ import barry_as_FLUFL >>> 1 <> 2 True