Python3 Operators
What is an operator?
This chapter mainly explains Python's operators.
Take a simple example:
4 + 5 = 9
In the example,4 and 5 are calledoperands, and + is called theoperator。
The Python language supports the following types of operators:
- Arithmetic operators
- Comparison (relational) operators
- Assignment operators
- Logical operators
- Bitwise operators
- member operators
- Identity operators
- Operator Precedence
Next let's learn Python's operators one by one.
Python arithmetic operators
Assume variable a=10 and variable b=21 below:
| operator | Description | Example |
|---|---|---|
| + | Add - adds two objects together | a + b outputs 31 |
| - | Subtract - yields a negative number or subtracts one number from another | a - b outputs -11 |
| * | Multiply - multiplies two numbers or returns a string repeated several times | a * b outputs 210 |
| / | Divide - x divided by y | b / a outputs 2.1 |
| % | Modulo - returns the remainder of a division | b % a outputs 1 |
| ** | Exponent - returns x raised to the power of y | a**b is 10 to the power of 21 |
| // | Floor division - rounds down to an integer |
>>> 9//2 |
4 >>> -9//2 -5 |
The following example demonstrates all of Python's arithmetic operators:
Example (Python 3.0+)
#!/usr/bin/python3
a
=
21
b
=
10
c
=
0
c
=
a
b
(
"
1 - the value of c is:
"
,
c
)
c
=
a
b
(
"
2 - the value of c is:
"
,
c
)
c
=
a
b
(
"
3 - the value of c is:
"
,
c
)
c
=
a
/
b
(
"
4 - the value of c is:
"
,
c
)
c
=
a
%
b
(
"
5 - the value of c is:
"
,
c
)
Modify variables a, b, and c
a
=
2
b
=
3
c
=
a
**
b
(
"
6 - the value of c is:
"
,
c
)
a
=
10
b
=
5
c
=
a
//
b
(
"
7 - the value of c is:
"
,
c
)
The example above produces the following output:
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
Assume variable a is 10 and variable b is 20 below:
| operator | Description | Example |
|---|---|---|
| == | Equal - checks whether objects are equal | (a == b) returns False. |
| != | Not equal - checks whether two objects are different | (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, which are equivalent to the special variables True and False. Note the capitalization of these variable names. | (a < b) returns True. |
| >= | Greater than or equal - returns whether x is greater than or equal to y. | (a >= b) returns False. |
| <= | Less than or equal - returns whether x is less than or equal to y. | (a <= b) returns True. |
The following example demonstrates all of Python's comparison operators:
Example (Python 3.0+)
#!/usr/bin/python3
a
=
21
b
=
10
c
=
0
if
(
a
==
b
)
:
(
"
1 - a equals b
"
)
else
:
(
"
1 - a does not equal b
"
)
if
(
a
!=
b
)
:
(
"
2 - a does not equal b
"
)
else
:
(
"
2 - a equals b
"
)
if
(
a
<
b
)
:
(
"
3 - a is less than b
"
)
else
:
(
"
3 - a is greater than or equal to b
"
)
if
(
a
b
)
:
(
"
4 - a is greater than b
"
)
else
:
(
"
4 - a is less than or equal to b
"
)
Modify the values of variables a and b
a
=
5
b
=
20
if
(
a
<=
b
)
:
(
"
5 - a is less than or equal to b
"
)
else
:
(
"
5 - a is greater than b
"
)
if
(
b
=
a
)
:
(
"
6 - b is greater than or equal to a
"
)
else
:
(
"
6 - b is less than a
"
)
The example above produces the following output:
1 - a 不等于 b
2 - a 不等于 b
3 - a 大于等于 b
4 - a 大于 b
5 - a 小于等于 b
6 - b 大于等于 a
Python assignment operators
Assume variable a is 10 and variable b is 20 below:
| 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 |
| %= | Modulo 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 assign a value and return that value within an expression at the same time.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 all of Python's assignment operators:
Example (Python 3.0+)
#!/usr/bin/python3
a
=
21
b
=
10
c
=
0
c
=
a
b
(
"
1 - the value of c is:
"
,
c
)
c
+=
a
(
"
2 - the value of c is:
"
,
c
)
c
*=
a
(
"
3 - the value of c is:
"
,
c
)
c
/=
a
(
"
4 - the value of c is:
"
,
c
)
c
=
2
c
%=
a
(
"
5 - the value of c is:
"
,
c
)
c
**=
a
(
"
6 - the value of c is:
"
,
c
)
c
//=
a
(
"
7 - the value of c is:
"
,
c
)
The example above produces the following output:
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, using the := symbol. Its main purpose is to assign a value and return that value within an expression at the same time.
Using the walrus operator can simplify code in some cases, especially when the assignment result is needed inside an expression. This is useful for simplifying loop conditions or repeated computations in expressions.
Below is a simple example demonstrating the use of the walrus operator:
Example
Traditional approach
n
=
10
if
n
5
:
(
n
)
Use the walrus operator
if
(
n :
=
10
)
5
:
(
n
)
if (n := 10) > 5:: this is the form using the walrus operator (:=). The walrus operator performs assignment inside an expression.(n := 10): Assign the value of the variablenis assigned the value 10 and that assignment result is returned.> 5: checks whether the assignednis greater than 5. If the condition is true, the following code block is executed.
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 inside expressions, which reduces code duplication and improves readability and conciseness. - In the example above, the traditional form needs a separate line to assign
nin the application context, then accessed this value inifand then check the condition in the statement. With the walrus operator, assignment and the condition check can be done directly in theifstatement.
Python bitwise operators
Bitwise operators treat numbers as binary. Python's bitwise operator rules are as follows:
In the table below, variable a is 60 and b is 13; their 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: for two values, if both corresponding bits are 1 the resulting bit is 1, otherwise 0 | (a & b) outputs 12, binary: 0000 1100 |
| | | Bitwise OR: if either of the two corresponding bits is 1, the resulting bit is 1. | (a | b) outputs 61, binary: 0011 1101 |
| ^ | Bitwise XOR: when the two corresponding bits differ, the result is 1 | (a ^ b) outputs 49, binary: 0011 0001 |
| ~ | Bitwise NOT: inverts each binary bit, turning 1 into 0 and 0 into 1. ~x is similar to -x-1 | (~a ) outputs -61, binary: 1100 0011, in the two's complement form of a signed binary number. |
| << | Left shift operator: all binary bits of the operand are shifted left by the number of positions specified by the value on the right of "<<"; high-order bits are discarded and low-order bits are filled with 0. | a << 2 outputs 240, binary: 1111 0000 |
| >> | Right shift operator: all binary bits of the operand on the left of ">>" are shifted right by the number of positions specified by the value on the right of ">>" | a >> 2 outputs 15, binary: 0000 1111 |
The following example demonstrates all of Python's bitwise operators:
Example (Python 3.0+)
#!/usr/bin/python3
a
=
60
60 = 0011 1100
b
=
13
13 = 0000 1101
c
=
0
c
=
a
&
b
12 = 0000 1100
(
"
1 - the value of c is:
"
,
c
)
c
=
a
|
b
61 = 0011 1101
(
"
2 - the value of c is:
"
,
c
)
c
=
a
^
b
49 = 0011 0001
(
"
3 - the value of c is:
"
,
c
)
c
= ~
a
-61 = 1100 0011
(
"
4 - the value of c is:
"
,
c
)
c
=
a
<<
2
240 = 1111 0000
(
"
5 - the value of c is:
"
,
c
)
c
=
a
2
15 = 0000 1111
(
"
6 - the value of c is:
"
,
c
)
The example above produces the following output:
1 - c 的值为: 12
2 - c 的值为: 61
3 - c 的值为: 49
4 - c 的值为: -61
5 - c 的值为: 240
6 - c 的值为: 15
Python logical operators
Python supports logical operators; assume variable a is 10 and b is 20 below:
| 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 computed 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 computed value of y. | (a or b) returns 10. |
| not | not x | Boolean "not" - if x is True, returns False; if x is False, returns True. | not(a and b) returns False |
The example above produces the following output:
Example (Python 3.0+)
#!/usr/bin/python3
a
=
10
b
=
20
if
(
a
and
b
)
:
(
"
1 - variables a and b are both true
"
)
else
:
(
"
1 - one of variables a and b is not true
"
)
if
(
a
or
b
)
:
(
"
2 - variables a and b are both true, or one of them is true
"
)
else
:
(
"
2 - neither variable a nor b is true
"
)
Modify the value of variable a
a
=
0
if
(
a
and
b
)
:
(
"
3 - variables a and b are both true
"
)
else
:
(
"
3 - one of variables a and b is not true
"
)
if
(
a
or
b
)
:
(
"
4 - variables a and b are both true, or one of them is true
"
)
else
:
(
"
4 - neither variable a nor b is true
"
)
if
not
(
a
and
b
)
:
(
"
5 - variables a and b are both false, or one of them is false
"
)
else
:
(
"
5 - variables a and b are both true
"
)
The example above produces the following output:
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, which test whether a sequence contains members, including strings, lists, or tuples.
| operator | Description | Example |
|---|---|---|
| in | Returns True if the value is found in the specified sequence, otherwise False. | x is in sequence y; returns True if x is in sequence y. |
| not in | Returns True if the value is not found in the specified sequence, otherwise False. | x is not in sequence y; returns True if x is not in sequence y. |
The following example demonstrates all of Python's membership operators:
Example (Python 3.0+)
#!/usr/bin/python3
a
=
10
b
=
20
list
=
[
1
,
2
,
3
,
4
,
5
]
if
(
a
in
list
)
:
(
"
1 - variable a is in the given list
"
)
else
:
(
"
1 - variable a is not in the given list
"
)
if
(
b
not
in
list
)
:
(
"
2 - variable b is not in the given list
"
)
else
:
(
"
2 - variable b is in the given list
"
)
Modify the value of variable a
a
=
2
if
(
a
in
list
)
:
(
"
3 - variable a is in the given list
"
)
else
:
(
"
3 - variable a is not in the given list
"
)
The example above produces the following output:
1 - 变量 a 不在给定的列表中 list 中
2 - 变量 b 不在给定的列表中 list 中
3 - 变量 a 在给定的列表中 list 中
Python identity operators
Identity operators compare the memory locations of two objects
| operator | Description | Example |
|---|---|---|
| is | is checks whether two identifiers refer to the same object | x is y, similar to id(x) == id(y) , returns True if they reference the same object, otherwise False |
| is not | is not checks whether two identifiers refer to different objects | ** x is not y** , similar to id(x) != id(y). Returns True if they do not reference the same object, otherwise False. |
Note: id() The function is used to get an object's memory address.
The following example demonstrates all of Python's identity operators:
Example (Python 3.0+)
#!/usr/bin/python3
a
=
20
b
=
20
if
(
a
is
b
)
:
(
"
1 - a and b have the same identity
"
)
else
:
(
"
1 - a and b do not have the same identity
"
)
if
(
id
(
a
)
==
id
(
b
)
)
:
(
"
2 - a and b have the same identity
"
)
else
:
(
"
2 - a and b do not have the same identity
"
)
Modify the value of variable b
b
=
30
if
(
a
is
b
)
:
(
"
3 - a and b have the same identity
"
)
else
:
(
"
3 - a and b do not have the same identity
"
)
if
(
a
is
not
b
)
:
(
"
4 - a and b do not have the same identity
"
)
else
:
(
"
4 - a and b have the same identity
"
)
The example above produces the following output:
1 - a 和 b 有相同的标识
2 - a 和 b 有相同的标识
3 - a 和 b 没有相同的标识
4 - a 和 b 没有相同的标识
Difference between is and ==:
is checks whether two variables reference the same object, while == checks whether the values of the referenced variables are equal.
Python operator precedence
The table below lists all operators from highest to lowest precedence. Operators in the same cell have the same precedence. Operators refer to binary operations unless stated otherwise. Operators in the same cell group left to right (except exponentiation, which groups right to left):
|
operator |
Description |
|---|---|
|
|
Parenthesized expressions |
|
|
Subscription, slicing, call, attribute reference |
|
await x |
await expression |
|
|
Exponentiation |
|
|
Unary plus, minus, bitwise NOT |
|
|
Multiplication, matrix multiplication, division, floor division, remainder |
|
|
Addition and subtraction |
|
|
Shift |
|
|
Bitwise AND |
|
|
Bitwise XOR |
|
|
Bitwise OR |
|
|
Comparisons, including membership tests and identity tests |
|
|
Logical NOT |
|
|
Logical AND |
|
|
Logical OR |
|
|
Conditional expression |
|
|
lambda expression |
|
|
Assignment expression |
The following example demonstrates operator precedence in Python:
Example (Python 3.0+)
#!/usr/bin/python3
a
=
20
b
=
10
c
=
15
d
=
5
e
=
0
e
=
(
a
b
)
c
/
d
#( 30 * 15 ) / 5
(
"
(a + b) * c / d evaluates to:
"
,
e
)
e
=
(
(
a
b
)
c
)
/
d
(30 * 15 ) / 5
(
"
((a + b) * c) / d evaluates to:
"
,
e
)
e
=
(
a
b
)
(
c
/
d
)
(30) * (15/5)
(
"
(a + b) * (c / d) evaluates to:
"
,
e
)
e
=
a
(
b
c
)
/
d
20 + (150/5)
(
"
a + (b * c) / d evaluates to:
"
,
e
)
The example above produces the following output:
(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
x
=
True
y
=
False
z
=
False
(
"
Case 1: default precedence (and is evaluated first)
"
)
if
x
or
y
and
z
:
Equivalent to x or (y and z)
(
"
yes
"
)
Will output
else
:
(
"
no
"
)
(
"
\n
Case 2: force a different precedence (or is evaluated first)
"
)
if
(
x
or
y
)
and
z
:
Add parentheses manually to change the order
(
"
yes
"
)
Will not output
else
:
(
"
no
"
)
Will output
In the example above, y and z is evaluated first and returns False, then x or False returns True, giving the output:
情况1:默认优先级(先算and)
yes
情况2:强制改变优先级(先算or)
no
Note:Python3 no longer supports the <> operator; you can use != instead. If you must use this kind of comparison operator, you can use the following approach:
>>> from __future__ import barry_as_FLUFL
>>> 1 <> 2 True