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:

Next, let's learn Python's operators one by one.


Python Arithmetic Operators

The following assumes variablea=10, variableb=21:

OperatorDescriptionExample
+Addition - Adds two objectsa + b outputs 31
-Subtraction - Gives a negative number or subtracts one number from anothera - b outputs -11
*Multiplication - Multiplies two numbers or returns a string repeated a certain number of timesa * b outputs 210
/Division - x divided by yb / a outputs 2.1
%Modulus - Returns the remainder of divisionb % a outputs 1
**Exponent - Returns x to the power of ya**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+)

#!/usr/bin/python3 a = 21 b = 10 c = 0 c = a + b print ("1 - the value of c is:", c) c = a - b print ("2 - the value of c is:", c) c = a * b print ("3 - the value of c is:", c) c = a / b print ("4 - the value of c is:", c) c = a % b print ("5 - the value of c is:", c) # Modify variables a, b, c a = 2 b = 3 c = a**b print ("6 - the value of c is:", c) a = 10 b = 5 c = a//b print ("7 - the value of c is:", c)

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:

OperatorDescriptionExample
==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+)

#!/usr/bin/python3 a = 21 b = 10 c = 0 if ( a == b ): print ("1 - a equals b") else: print ("1 - a is not equal to b") if ( a != b ): print ("2 - a is not equal to b") else: print ("2 - a equals b") if ( a < b ): print ("3 - a is less than b") else: print ("3 - a is greater than or equal to b") if ( a > b ): print ("4 - a is greater than b") else: print ("4 - a is less than or equal to b") # Modify the values of variables a and b a = 5 b = 20 if ( a <= b ): print ("5 - a is less than or equal to b") else: print ("5 - a is greater than b") if ( b >= a ): print ("6 - b is greater than or equal to a") else: print ("6 - b is less than a")

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:

OperatorDescriptionExample
=Simple assignment operatorc = a + b assigns the result of a + b to c
+=Addition assignment operatorc += a is equivalent to c = c + a
-=Subtraction assignment operatorc -= a is equivalent to c = c - a
*=Multiplication assignment operatorc *= a is equivalent to c = c * a
/=Division assignment operatorc /= a is equivalent to c = c / a
%=Modulus assignment operatorc %= a is equivalent to c = c % a
**=Exponent assignment operatorc **= a is equivalent to c = c ** a
//=Floor division assignment operatorc //= 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+)

#!/usr/bin/python3 a = 21 b = 10 c = 0 c = a + b print ("1 - the value of c is:", c) c += a print ("2 - the value of c is:", c) c *= a print ("3 - the value of c is:", c) c /= a print ("4 - the value of c is:", c) c = 2 c %= a print ("5 - the value of c is:", c) c **= a print ("6 - the value of c is:", c) c //= a print ("7 - the value of c is:", c)

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

# Traditional approach
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 assignn, 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
OperatorDescriptionExample
&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+)

#!/usr/bin/python3 a = 60 # 60 = 0011 1100 b = 13 # 13 = 0000 1101 c = 0 c = a & b # 12 = 0000 1100 print ("1 - The value of c is:", c) c = a | b # 61 = 0011 1101 print ("2 - The value of c is:", c) c = a ^ b # 49 = 0011 0001 print ("3 - The value of c is:", c) c = ~a # -61 = 1100 0011 print ("4 - The value of c is:", c) c = a << 2 # 240 = 1111 0000 print ("5 - The value of c is:", c) c = a >> 2 # 15 = 0000 1111 print ("6 - The value of c is:", c)

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:

OperatorLogical expressionDescriptionExample
andx and yBoolean 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.
orx or yBoolean OR - If x is True, it returns the value of x; otherwise, it returns the evaluated value of y.(a or b) returns 10.
notnot xBoolean 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+)

#!/usr/bin/python3 a = 10 b = 20 if ( a and b ): print ("1 - Variables a and b are both true") else: print ("1 - One of the variables a and b is not true") if ( a or b ): print ("2 - Variables a and b are both true, or one of the variables is true") else: print ("2 - Variables a and b are both not true") # Modify the value of variable a a = 0 if ( a and b ): print ("3 - Variables a and b are both true") else: print ("3 - One of the variables a and b is not true") if ( a or b ): print ("4 - Variables a and b are both true, or one of the variables is true") else: print ("4 - Variables a and b are both not true") if not( a and b ): print ("5 - Variables a and b are both false, or one of the variables is false") else: print ("5 - Variables a and b are both true")

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.

OperatorDescriptionExample
inReturns 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 inReturns 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+)

#!/usr/bin/python3 a = 10 b = 20 list = [1, 2, 3, 4, 5 ] if ( a in list ): print ("1 - Variable a is in the given list list") else: print ("1 - Variable a is not in the given list list") if ( b not in list ): print ("2 - Variable b is not in the given list list") else: print ("2 - Variable b is in the given list list") # Modify the value of variable a a = 2 if ( a in list ): print ("3 - Variable a is in the given list list") else: print ("3 - Variable a is not in the given list list")

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.

OperatorDescriptionExample
isis 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 notis 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+)

#!/usr/bin/python3 a = 20 b = 20 if ( a is b ): print ("1 - a and b have the same identity") else: print ("1 - a and b do not have the same identity") if ( id(a) == id(b) ): print ("2 - a and b have the same identity") else: print ("2 - a and b do not have the same identity") # Modify the value of variable b b = 30 if ( a is b ): print ("3 - a and b have the same identity") else: print ("3 - a and b do not have the same identity") if ( a is not b ): print ("4 - a and b do not have the same identity") else: print ("4 - a and b have the same identity")

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

(expressions...),

[expressions...], {key: value...}, {expressions...}

Parenthesized expressions

x[index], x[index:index], x(arguments...), x.attribute

Subscription, slicing, call, attribute reference

await x

await expression

**

Exponentiation (power)

+x, -x, ~x

Positive, negative, bitwise NOT

*, @, /, //, %

Multiplication, matrix multiplication, division, floor division, remainder

+, -

Addition and subtraction

<<, >>

Shifts

&

Bitwise AND

^

Bitwise XOR

|

Bitwise OR

in,not in, is,is not, <, <=, >, >=, !=, ==

Comparisons, including membership tests and identity tests

not x

Boolean NOT

and

Boolean AND

or

Boolean OR

if -- else

Conditional expression

lambda

lambda expression

:=

Assignment expression

The following examples demonstrate the operations of all Python operator precedence:

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 print ("The result of (a + b) * c / d is:", e) e = ((a + b) * c) / d # (30 * 15 ) / 5 print ("The result of ((a + b) * c) / d is:", e) e = (a + b) * (c / d) # (30) * (15/5) print ("The result of (a + b) * (c / d) is:", e) e = a + (b * c) / d # 20 + (150/5) print ("The result of a + (b * c) / d is:", e)

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

x = True y = False z = False print("Case 1: Default precedence (evaluating and first)") if x or y and z: # Equivalent to x or (y and z) print("yes") # Will output else: print("no") print("\nCase 2: Forced precedence change (evaluating or first)") if (x or y) and z: # Manually add parentheses to change the order print("yes") # Will not output else: print("no") # Will output

The above example first evaluatesy and zand returns False, thenx or Falsereturns True, and the output result is:

情况1:默认优先级(先算and)
yes

情况2:强制改变优先级(先算or)
no

Note: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
Other extensions