Operators and expressions that must be mastered in Python

Learn Python data science, play games, learn Japanese, and engage in programming all in one package.

The content shared this time is the operation of Python operators and expressions.

The data used in the whole set of self-study courses are the contents of the games of "Three Kingdoms" and "Three Kingdoms Warriors" series.

Python can create complex expressions by combining objects and operators. Operators are special symbols that indicate that some kind of calculation should be performed.

a = 1
b = 2
a + b
3

a + b - 5
-2

a + b and a + b - 5 are called expressions. Python supports a number of operators that combine data objects into expressions.

insert image description here

arithmetic operators

Arithmetic operators supported by Python assume variables: a=10, b=20

expression Symbol Description Results of the
+ add - add two objects a + b outputs the result 30
- Subtract - get a negative number or subtract one number from another a - b output result -10
* multiply - multiply two numbers or return a string repeated several times a * b output result 200
/ divide - x divided by y b / a output result 2
% modulo - returns the remainder of the division b % a output result is 0
** power - returns x raised to the y power a**b is 10 to the 20th power, and the output result is 100000000000000000000
// Round Divide - Returns the integer part of the quotient (rounded down) 9//2 is 4; -9//2 is 5

Please add image description

a = 4
b = 3

+a
4

-b
-3

a + b
7

a - b
1

a * b
12

a / b
1.3333333333333333

a % b
1

a ** b
64

comparison operator

symbol expression Symbol Description Results of the
== a == b equal a and b have the same value
!= a != b not equal to a and b are not equal
< a < b less than The value of a is less than the value of b
<= a <= b less than or equal to The value of a is less than or equal to b
> a > b more than the The value of a is greater than the value of b
>= a >= b greater than or equal to The value of a is greater than or equal to b
a = 10
b = 20

a == b
False

a != b
True

a <= b
True

a >= b
False

a = 30
b = 30

a == b
True

a <= b
True

a >= b
True

special floating-point value equality comparisons

The comparison of floating-point numbers is not a direct comparison.

x = 1.1 + 2.2
x == 3.3
False

The preferred way to determine whether two floating-point values ​​are equal is to calculate whether they are close to each other, given some tolerance. Use abs() to return the absolute value. If the absolute value of the difference between two numbers is less than the specified tolerance, they are close enough to each other to be considered equal.

tolerance = 0.00001
x = 1.1 + 2.2
abs(x - 3.3) < tolerance
True

Logical Operators

insert image description here

logical expressions for boolean operands

x = 5
x < 10
True
type(x < 10)
<class 'bool'>

t = x > 10
t
False
type(t)
<class 'bool'>

callable(x)
False
type(callable(x))
<class 'bool'>

t = callable(len)
t
True
type(t)
<class 'bool'>
symbol Expression example Symbol Description
not not x < 10 non-meaning
or x < 10 or callable(x) or
and x < 10 and callable(x) and

or compound logical expression

Multiple logical operators and operands can be strung together to form compound logical expressions, using a method called McCarthy evaluation, where any element is true, then the entire expression is true.

x1 or x2 or x3 or … xn

def f(n):
	return n

f(0) or f(False) or f(1) or f(2) or f(3)
-> f(0) = 0 
-> f(False) = False
-> f(1) = 1
1

and compound expression

Multiple logical operators and operands can be strung together to form a compound logical expression that is true if all in xi are true.

x1 and x2 and  x3 and  … xn

def f(n):
	return n

f(1) and f(False) and f(2) and f(3)
-> f(1) = 1
-> f(False) = False
False

f(1) and f(0.0) and f(2) and f(3)
-> f(1) = 1
-> f(0.0) = 0.0
0.0

f(1) and f(2.2) and f('data')
-> f(1) = 1
-> f(2.2) = 2.2
-> f(data) = data
'data'

short circuit evaluation

Used in idiomatic patterns to succinctly express avoiding unusual operations using short-circuit evaluation.

Two variables a and b are defined for judgment.

# 常规操作
a = 3
b = 1
(b / a) > 0
True

# 意外情况,解释器引发异常
a = 0
b = 1
(b / a) > 0
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    (b / a) > 0
ZeroDivisionError: division by zero

# 可以使用这样的表达式来避免错误
a = 0
b = 1
a != 0 and (b / a) > 0
False

# 更简洁的表达方式
a = 0
b = 1
a and (b / a) > 0
0

Defines the default value method, specifying that the default value is selected when the value is zero or empty.

s = string or '<default_value>'

# string为非空,则为真
string = 'data'
s = string or '<default_value>'
s
'data'

# string是一个空字符串,则为假
string = ''
s = string or '<default_value>'
s
'<default_value>'

chain comparison

Comparison operators can be chained to arbitrary lengths.

x < y <= z
# 等价于
x < y and y <= z

x < f() <= z
# 等价于
x < f() and f() <= z

bitwise operators

Bitwise operators treat their operands as sequences of binary numbers and operate on them bit by bit.
insert image description here

symbol expression meaning Symbol Description
& a & b bitwise AND 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 bitwise OR Bitwise OR: As long as one of the corresponding two binary bits is 1, the result bit is 1.
~ ~a bitwise negation Bitwise negation operator: Negates each binary bit of the data, that is, changes 1 to 0 and 0 to 1.
^ a ^ b Bitwise XOR (XOR) Bitwise XOR Operator: When two corresponding binary bits are different, the result is 1
>> a >> n shift right n positions Right shift operator: shift all the binary bits of the operand on the left of ">>" by a number of bits, and the number on the right of >> specifies the number of bits to move
<< a << n shift left n positions Left shift operator: All binary bits of the operand are shifted to the left by several bits, the number of bits to be shifted is specified by the number on the right of <<, the high bits are discarded, and the low bits are filled with 0.
# 0b1010 = 10
# 0b1100 = 12

'0b{:04b}'.format(0b1100 & 0b1010)
'0b1000'
'0b{:04b}'.format(0b1100 | 0b1010)
'0b1110'
'0b{:04b}'.format(0b1100 ^ 0b1010)
'0b0110'
'0b{:04b}'.format(0b1100 >> 2)
'0b0011'
'0b{:04b}'.format(0b0011 << 2)
'0b1100'

identity operator

Python provides two operators is and is not, which determine whether the given operands have the same identity, that is, refer to the same object. Unlike equality, this means that both operands refer to objects that contain the same data but are not necessarily the same object.
insert image description here

x = 1001
y = 1000 + 1
print(x, y)
1001 1001

x == y
True
x is y
False

# 虽然值相等 但是引用对象不一样
id(x)
2643115955696
id(y)
2643115956944

operator precedence

insert image description here

The precedence order of Python operators, from low to high.

symbol Symbol description
or boolean or
and boolean with
not Buffalo
==, !=, <, <=, >, >=, is,is not compare, identity
| bitwise OR
^ Bitwise XOR
& bitwise AND
<<,>> displacement
+,- addition, subtraction
*, /, //,% Multiplication, division, division, modulo
+x, -x,~x Unary positive, unary negative, bitwise negation
** exponentiation
2 * 3 ** 4 * 5
810

Expressions in parentheses are always executed first.

20 + 4 * 10
60

(20 + 4) * 10
240

Useless parentheses.

(a < 10) and (b > 30)
# 等价于
a < 10 and b > 30

Augmented assignment operator

It is perfectly fine for the value on the right-hand side of the assignment to be an expression containing other variables.

a = 10
b = 20
c = a * 5 + b
c
70

a = 10
a = a + 5
a
15

b = 20
b = b * 3
b
60

Incorrect usage, use variable before and assign value.

z = z / 12
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    z = z / 12
NameError: name 'z' is not defined

Shorthand.

shorthand Standard notation
a += 5 a = a + 5
a /= 10 a = a / 10
a ^= b a = a ^ b

Guess you like

Origin blog.csdn.net/qq_20288327/article/details/124389000