Python Introductory Tutorial | Python3 Operators

What is an operator?

In Python, operators are special symbols used to perform various operations. Whether you're doing math, logic, or some other type of operation, you can use the right operator to do it. To give a simple example:

4 + 5 = 9

In the example, 4 and 5 are called operands and + is called operator.
This article will explain in detail the common operators in Python 3.

arithmetic operator

Arithmetic operators are used to perform basic mathematical operations.

  1. Addition (+): Adds two values.
  2. Subtraction (-): Subtracts the second value from the first value.
  3. Multiplication (*): Multiplies two values.
  4. Division (/): Divides the first value by the second value to get a floating point result.
  5. Divisibility (//): Divides the first value by the second value, resulting in an integer result (rounded down).
  6. Modulo (%): Computes the remainder when dividing two values.
  7. Exponentiation (**): Raises the first value to the power of the exponent as the second value.

The following examples demonstrate the operation of all Python arithmetic operators:

a = 21
b = 10
c = 0
 
c = a + b
print ("1 - c 的值为:", c)
 
c = a - b
print ("2 - c 的值为:", c)
 
c = a * b
print ("3 - c 的值为:", c)
 
c = a / b
print ("4 - c 的值为:", c)
 
c = a % b
print ("5 - c 的值为:", c)
 
# 修改变量 a 、b 、c
a = 2
b = 3
c = a**b 
print ("6 - c 的值为:", c)
 
a = 10
b = 5
c = a//b 
print ("7 - c 的值为:", c)

assignment operator

Assignment operators are used to copy a value to a variable.
The following assumes that variable a is 10 (a=10) and variable b is 21 (b=21):

operator describe example
simple assignment (=) Assign the value on the right to the variable on the left c = a + b assign the operation result of a + b to c
Addition assignment (+=) Add the value on the right to the variable on the left and assign the result to the variable on the left c = a + b assign the operation result of a + b to c
Subtraction assignment (-=) Subtracts the value on the right from the variable on the left and assigns the result to the variable on the left c -= a is equivalent to c = c - a
multiplication assignment (*=) Multiplies the value on the right with the variable on the left and assigns the result to the variable on the left c *= a is equivalent to c = c * a
Division assignment (/=) Divides the variable on the left by the value on the right and assigns the result to the variable on the left c /= a is equivalent to c = c / a
Modulo assignment (%=) Take the remainder from the variable on the left and the variable on the right, and assign the result to the variable on the left c %= a is equivalent to c = c % a
power assignment (**=) Evaluates the variable on the right as an exponential power of the variable on the left and assigns the result to the variable on the left c **= a is equivalent to c = c ** a
Integer assignment (//=) Divide the variable on the left by the value on the right to get the integer result (rounded down) and assign it to the variable on the left c //= a is equivalent to c = c // a
walrus assignment (:=) The walrus operator, which can be used to assign values ​​to variables inside expressions. New operators in Python 3.8 (n := len(str)) > 10

Usually, when evaluating a condition or expression, we need to calculate the value of the expression before comparing it with a variable. With the walrus operator, you can directly assign a value to a variable in a judgment condition or expression, and return the assigned value as the result of the entire expression. Quite simplified, (n := len(str)) > 10 is equivalent to n = len(str); n>10. (The len() method is to find the length of a string or a collection. pyhton does not need to be added after each line of code like java; when multiple expressions are written on one line, they need to be separated by ;) The following example demonstrates all assignment operators in
Python The operation:

a = 21
b = 10
c = 0
 
c = a + b
print ("1 - c 的值为:", c)
 
c += a
print ("2 - c 的值为:", c)
 
c *= a
print ("3 - c 的值为:", c)
 
c /= a 
print ("4 - c 的值为:", c)
 
c = 2
c %= a
print ("5 - c 的值为:", c)
 
c **= a
print ("6 - c 的值为:", c)
 
c //= a
print ("7 - c 的值为:", c)

comparison operator

Comparison operators are used to compare the relationship between two values ​​and return a Boolean value (True or False).

  1. Equals (==): Returns True if two values ​​are equal.
  2. Not Equal (!=): Returns True if two values ​​are not equal.
  3. Greater than (>): Returns True if the first value is greater than the second value.
  4. Less Than (<): Returns True if the first value is less than the second value.
  5. Greater than or equal to (>=): Returns True if the first value is greater than or equal to the second value.
  6. Less than or equal to (<=): Returns True if the first value is less than or equal to the second value.

The following examples demonstrate the operation of all Python comparison operators:

a = 21
b = 10
c = 0
 
if ( a == b ):
   print ("1 - a 等于 b")
else:
   print ("1 - a 不等于 b")
 
if ( a != b ):
   print ("2 - a 不等于 b")
else:
   print ("2 - a 等于 b")
 
if ( a < b ):
   print ("3 - a 小于 b")
else:
   print ("3 - a 大于等于 b")
 
if ( a > b ):
   print ("4 - a 大于 b")
else:
   print ("4 - a 小于等于 b")
 
# 修改变量 a 和 b 的值
a = 5
b = 20
if ( a <= b ):
   print ("5 - a 小于等于 b")
else:
   print ("5 - a 大于  b")
 
if ( b >= a ):
   print ("6 - b 大于等于 a")
else:
   print ("6 - b 小于 a")

Logical Operators

Logical operators are used to operate on Boolean values.

  1. And (and): Returns True if both conditions are True.
  2. Or (or): Returns True if at least one condition is True.
  3. Not (not): Negates the given condition.

The following examples demonstrate the operation of all Python comparison operators:

a = 10
b = 20
 
if ( a and b ):
   print ("1 - 变量 a 和 b 都为 true")
else:
   print ("1 - 变量 a 和 b 有一个不为 true")
 
if ( a or b ):
   print ("2 - 变量 a 和 b 都为 true,或其中一个变量为 true")
else:
   print ("2 - 变量 a 和 b 都不为 true")
 
# 修改变量 a 的值
a = 0
if ( a and b ):
   print ("3 - 变量 a 和 b 都为 true")
else:
   print ("3 - 变量 a 和 b 有一个不为 true")
 
if ( a or b ):
   print ("4 - 变量 a 和 b 都为 true,或其中一个变量为 true")
else:
   print ("4 - 变量 a 和 b 都不为 true")
 
if not( a and b ):
   print ("5 - 变量 a 和 b 都为 false,或其中一个变量为 false")
else:
   print ("5 - 变量 a 和 b 都为 true")

member operator

Membership operators are used to check whether a value belongs to a sequence (such as a string, list or tuple).

  1. in: Returns True if the value is in the sequence.
  2. not in: Returns True if the value is not in the sequence.

The following examples demonstrate the operation of all Python membership operators:

a = 10
b = 20
list = [1, 2, 3, 4, 5 ]
 
if ( a in list ):
   print ("1 - 变量 a 在给定的列表中 list 中")
else:
   print ("1 - 变量 a 不在给定的列表中 list 中")
 
if ( b not in list ):
   print ("2 - 变量 b 不在给定的列表中 list 中")
else:
   print ("2 - 变量 b 在给定的列表中 list 中")
 
# 修改变量 a 的值
a = 2
if ( a in list ):
   print ("3 - 变量 a 在给定的列表中 list 中")
else:
   print ("3 - 变量 a 不在给定的列表中 list 中")

identity operator

Identity operators are used to compare the memory addresses of two objects.

  1. is: Returns True if two objects have the same memory address.
  2. is not: Returns True if the two objects have different memory addresses.

The following example demonstrates the operation of all Python identity operators:
Note : The id() function is used to obtain the object memory address.

a = 20
b = 20
 
if ( a is b ):
   print ("1 - a 和 b 有相同的标识")
else:
   print ("1 - a 和 b 没有相同的标识")
 
if ( id(a) == id(b) ):
   print ("2 - a 和 b 有相同的标识")
else:
   print ("2 - a 和 b 没有相同的标识")
 
# 修改变量 b 的值
b = 30
if ( a is b ):
   print ("3 - a 和 b 有相同的标识")
else:
   print ("3 - a 和 b 没有相同的标识")
 
if ( a is not b ):
   print ("4 - a 和 b 没有相同的标识")
else:
   print ("4 - a 和 b 有相同的标识")

The difference between is and == :

is is used to judge whether two variable reference objects are the same, and == is used to judge whether the values ​​of reference variables are equal.

a = 20
b = 20

if ( a is b ):
   print ("1 - a 和 b 有相同的标识")
else:
   print ("1 - a 和 b 没有相同的标识")
 
if ( id(a) == id(b) ):
   print ("2 - a 和 b 有相同的标识")
else:
   print ("2 - a 和 b 没有相同的标识")
 
# 修改变量 b 的值
b = 30
if ( a is b ):
   print ("3 - a 和 b 有相同的标识")
else:
   print ("3 - a 和 b 没有相同的标识")
 
if ( a is not b ):
   print ("4 - a 和 b 没有相同的标识")
else:
   print ("4 - a 和 b 有相同的标识")

bitwise operator

Bitwise operators perform calculations on numbers as if they were binary. The bitwise operation algorithm in Python is as follows:

In the table below, variable a is 60, and b is 13. The binary format is as follows:

a = 0011 1100
b = 0000 1101
operator describe example
& Bitwise AND operator: Two values ​​involved in the operation, if both corresponding bits are 1, the result of the bit is 1, otherwise it is 0 (a & b) output result 12, binary interpretation: 0000 1100
| Bitwise OR operator: as long as one of the corresponding two binary bits is 1, the result bit is 1 (a | b) output result 61, binary interpretation: 0011 1101
^ Bitwise XOR operator: When two corresponding binary bits are different, the result is 1 (a ^ b) output 49, binary interpretation: 0011 0001
~ Bitwise inversion operator: Inverts each binary bit of the data, that is, turns 1 into 0 and 0 into 1. ~x is like -x-1 (~a) outputs -61, binary interpretation: 1100 0011, in a signed binary number's complement form
<< Left shift operator: each binary bit of the operand is shifted to the left by several bits, and the number of bits to move is specified by the number on the right of "<<", the high bit is discarded, and the low bit is filled with 0 a << 2 output result 240, binary interpretation: 1111 0000
>> Right shift operator: Shift all the binary bits of the operand on the left of ">>" to the right by a certain number of bits, and the number on the right of ">>" specifies the number of bits to move a >> 2 output result 15, binary interpretation: 0000 1111

The following examples demonstrate the operation of all bitwise operators in Python:

a = 60            # 60 = 0011 1100 
b = 13            # 13 = 0000 1101 
c = 0
 
c = a & b        # 12 = 0000 1100
print ("1 - c 的值为:", c)
 
c = a | b        # 61 = 0011 1101 
print ("2 - c 的值为:", c)
 
c = a ^ b        # 49 = 0011 0001
print ("3 - c 的值为:", c)
 
c = ~a           # -61 = 1100 0011
print ("4 - c 的值为:", c)
 
c = a << 2       # 240 = 1111 0000
print ("5 - c 的值为:", c)
 
c = a >> 2       # 15 = 0000 1111
print ("6 - c 的值为:", c)

operator precedence

The following table lists all operators from highest to lowest precedence, with operators within the same cell having the same precedence. Operators refer to binary operations, unless otherwise noted. Operators within the same cell are grouped from left to right (except that exponentiation is grouped from right to left):

operator describe
(expressions…),[expressions…], {key: value…}, {expressions…} parenthesized expressions
x[index], x[index:index], x(arguments…), x.attribute read, slice, call, property reference
await x await expression
** power (exponent)
+x, -x, ~x Positive, Negative, Bitwise NOT
*, @, /, //, % multiply, matrix multiply, divide, divisible, remainder
+, - add and subtract
<<, >> shift
& bitwise AND
^ bitwise XOR
| bitwise OR
in,not in, is,is not, <, <=, >, >=, !=, == Comparison operations, including membership checks and identification number checks
not x logical NOT
and Logic and AND
or logical OR
if – else conditional expression
lambda lambda expression
:= assignment expression

The following example demonstrates the operation of all Python operator precedence:

a = 20
b = 10
c = 15
d = 5
e = 0
 
e = (a + b) * c / d       #( 30 * 15 ) / 5
print ("(a + b) * c / d 运算结果为:",  e)
 
e = ((a + b) * c) / d     # (30 * 15 ) / 5
print ("((a + b) * c) / d 运算结果为:",  e)
 
e = (a + b) * (c / d)    # (30) * (15/5)
print ("(a + b) * (c / d) 运算结果为:",  e)
 
e = a + (b * c) / d      #  20 + (150/5)
print ("a + (b * c) / d 运算结果为:",  e)

x = True
y = False
z = False
 
if x or y and z:
    print("yes")
else:
    print("no")

Note : Python3 does not support the <> operator, you can use != instead.

Guess you like

Origin blog.csdn.net/weixin_40986713/article/details/132524359