"Learning Python with You Hand in Hand" 13-Operation

In the previous article "Learning Python with You Hand in Hand" 12-Numbers , we learned about the types, operations, functions and other content of numbers. In this article, we will continue to expand the types of operations in Python based on number operations. There may be some calculation methods that we don't usually touch, but the overall difficulty is not big.

First, we first define two concepts, one is called operand and the other is called operator. In the simplest form of 1+2, 1 and 2 are the operands, and + is the operator.

Second, we define a classification method for the operation. According to the number of operands, operations can be divided into unary operations, binary operations and ternary operations. For example, the operand of -2 has only one 2, which is a unary operation. The operands of 1+2 are 1 and 2, which are binary operations. Because the ternary operation will involve the judgment function we will introduce later, we will not mention it for the time being. As for quaternary or more operations, there may be, but no one says that.

Finally, let's take a brief look at unary operations. Unary operations are relatively simple because they have only one operand. Correspondingly, there are just a few unary operators. Generally, the unary operators we will use are positive (+) and negative (-).

After making the above small foreshadowing, we begin today's topic-Python operations, or more precisely, Python's binary operations.

What we are most exposed to is binary operations, including the arithmetic operations, comparisons, inclusions, logical operations, etc. that we usually call, all of which belong to binary operations.

It's just that in Python, we use computer language to standardize the binary operations mentioned above and we may usually come into contact with them, but we don't think that it is also a kind of operation. It is divided into the following 7 categories:

Arithmetic operation

Assignment operation

Comparison operation

logic operation

Member operation

Identity computing

Bit operation

Below, we will explain the binary operations of Python one by one according to these seven categories.

1. Arithmetic operations

Regarding arithmetic operations, a detailed introduction has been given in the previous article "Learning Python with You Hand in Hand" 12-Numbers . I won't repeat it in this article. Please move on to understand.

2. Assignment operation

The assignment operation is derived from the arithmetic operation, because the assignment operation actually performs two processes-first arithmetic operation and then assignment, and this assignment is to the operand on the left side of the assignment operator. for example:

c = a + b is to assign the result of a and b to c. This is just ordinary arithmetic operation and then assignment.

In the same way, a = a + b is just an ordinary arithmetic operation and then assignment, but the result of the operation is assigned to one of the operands. But when a = a + b is written as equivalent a += b, it becomes an assignment operation. A + b is executed first, and then the value of a + b is assigned to the operand a on the left side of the assignment operator.

All arithmetic operations can become assignment operations by adding an = sign after the arithmetic operator.

In [1]: a = 11
        b = 3
In [2]: a += b
        a
Out[2]: 14
In [3]: a = 11
        a -= b
        a
Out[3]: 8
In [4]: a = 11
        a *= b
        a
Out[4]: 33
In [5]: a = 11
        a /= b
        a
Out[5]: 3.6666666666666665
In [6]: a = 11
        a **= b   # a的b次幂
        a
Out[6]: 1331

In [7]: a = 11
        a %= b   # 11除3等于3,余数为2
        a
Out[7]: 2
In [8]: a = 11
        a //= b   # 11除3等于3余2,向下取整数部分为3
        a
Out[8]: 3

In the above example, because a is assigned, the value of a will change, so you need to assign a to 11 before executing the next instance.

3. Comparison operation

Comparison operations are commonly used in mathematics for greater than (>), less than (<), equal to (==), not equal to (!=), and greater than or equal to (>=), less than or equal to (<=).

Because in computer language, "=" has been used as an assignment symbol, so all equal signs are represented by "=". There are also mathematical symbols that are different from the ones we usually use, including "!=", ">=" and "<=". Just pay attention when you use them.

The result of the comparison operation is represented by a Boolean value, which is the True and False (case fixed expression) we mentioned before. In addition to comparison operations, Boolean values ​​will also be applied to logical operations, membership operations, and identity operations that we will talk about in a while.

In [9]: a = 2
        b = 3
In [10]: a > b
Out[10]: False
In [11]: a < b
Out[11]: True
In [12]: a == b
Out[12]: False
In [13]: a != b
Out[13]: True
In [14]: a >= b
Out[14]: False
In [15]: a <= b
Out[15]: True

4. Logic operations

Before we talk about logical operations, we need to explain Boolean values ​​in depth.

As we said before, there are two boolean values, namely True for true and False for false. In addition to True and False, true and false can also be represented by 1 and 0, or 1 and 0 are the numerical forms of True and False respectively. And because True and False have numerical forms, arithmetic operations can be performed.

In [16]: True + True
Out[16]: 2
In [17]: True - False
Out[17]: 1
In [18]: True * 5
Out[18]: 5
In [19]: True * False
Out[19]: 0

One last sentence. In the logical operation to be discussed next, the range of representing "true" is larger. All numbers that are not 0 represent "logical truth", and only 0 represents "logical false".

There are three types of logical operations, namely and, or, and not.

and stands for "and". For the form of a and b, if a is True or "logically true" (that is, all non-zero numbers), the value of a and b is equal to b. If a is False or "logically false" (ie 0), the values ​​of a and b are equal to False or 0 (consistent with whether the value of a is False or 0).

In [20]: a = True   # a为True,结果等于b
         b = 5
         a and b
Out[20]: 5
In [21]: a = -8.5   # a为非0数字,相当于True,结果等于b
         b = 5
         a and b
Out[21]: 5
In [22]: a = False   # a为Fasle,结果为False
         b = 5
         a and b
Out[22]: False
In [23]: a = 0   # a为0,相当于False,结果为0
         b = 5
         a and b
Out[23]: 0

or stands for "or". For the form of a or b, if a is True or "logically true" (that is, all non-zero numbers), the value of a or b is equal to a. If a is False or "logically false" (ie 0), the value of a or b is equal to b.

In [24]: a = True   # a为True,结果等于a
         b = 5
         a or b
Out[24]: True
In [25]: a = -8.5   # a为非0数字,相当于True,结果等于a
         b = 5
         a or b
Out[25]: -8.5
In [26]: a = False   # a为False,结果等于b
         b = 5
         a or b
Out[26]: 5
In [27]: a = 0   # a为0,相当于False,结果等于b
         b = 5
         a or b
Out[27]: 5

not stands for "not". For the form of not a, if a is True or "logically true" (that is, all non-zero numbers), the value of not a is equal to False (there is no case equal to 0). If a is False or "logically false" (ie 0), the value of not a is equal to True (there is no case that is equal to a non-zero number).

In [28]: a = True   # a为True,结果等于False
         not a
Out[28]: False
In [29]: a = -8.5   # a为非0数字,相当于True,结果等于False
         not a
Out[29]: False
In [30]: a = False   # a为False,结果等于True
         not a
Out[30]: True
In [31]: a = 0   # a为0,相当于False,结果等于True
         not a
Out[31]: True

5. Member calculation

There are two types of membership operations, in and not in. Member operations can be directly understood literally, that is, operations to determine whether they are members.

For in, if the value can be found in the specified sequence, it returns True, otherwise it returns False. For not in, if the value cannot be found in the specified sequence, it returns True, otherwise it returns False.

In [32]: a = 2
         b = 0
         lst = [1, 2, 3, 4, 5]
In [33]: a in lst
Out[33]: True
In [34]: b in lst
Out[34]: False
In [35]: a not in lst
Out[35]: False
In [36]: b not in lst
Out[36]: True

6. Identity computing

Identity operation is used to compare whether two objects point to the same memory address. There are two types of identity operation: is and not is.

For is, if the memory addresses of the two variables are the same, it returns True, otherwise it returns False. For not is, if the memory addresses of the two variables are different, return True, otherwise return False.

To understand identity computing, you need to first understand the storage mechanism of Python.

Usually we call variables, such as a = 1, what we can see is the name of the variable (name) a, and the value of the variable (value) 1. In fact, there is another attribute that we can't see, that is the variable The stored memory address (id), the storage address can be obtained using the id() function.

Before we learned == in comparison operations, it is actually to judge whether the values ​​of two variables are equal. The identity calculation judges whether the memory addresses (id) of two variables are equal.

Therefore, in general, although we seem to have the same value (value) of two variables, their memory addresses (id) are not necessarily the same.

In [37]: a = 'Hello World!'
         b = 'Hello World!'
         print("比较结果:a == b:{};a is b:{}。".format(a == b, a is b))   # ab都是相同的字符串,值相同,但是内存地址不同
Out[37]: 比较结果:a == b:True;a is b:False。

So under what circumstances, the value of the variable is the same, and the memory address is also the same? Because whether we use it or not, Python pre-caches all integers between -5 (inclusive) and 257 (exclusive), so there are only these 262 integers, as long as the value is the same, the memory address is the same. (It can be understood here that the intervals in Python are all left-closed and right-opened, so I will not say between -5 and 256.)

In [38]: a = 5
         b = 5
         print("比较结果:a == b:{};a is b:{}。".format(a == b, a is b))   # ab在-5~257的左闭右开区间内,值相同,内存地址也相同
Out[38]: 比较结果:a == b:True;a is b:True。
In [39]: a = 257
         b = 257
         print("比较结果:a == b:{};a is b:{}。".format(a == b, a is b))   # ab不在-5~257的左闭右开区间内,值相同,但内存地址不同
Out[39]: 比较结果:a == b:True;a is b:False。
In [40]: a = -6
         b = -6
         print("比较结果:a != b:{};a is  not b:{}。".format(a != b, a is not b))   # ab不在-5~256的全闭区间内,值相同,但内存地址不同
Out[40]: 比较结果:a != b:False;a is  not b:True。

Give another example that needs attention.

When we want to copy a variable in the process of program running or debugging, it is easy to think of using b = a to copy. When we modify the value of b, it will not affect the value of a. But the world is sometimes not as simple as we think. Although we copied a with b, since a and b point to the same storage unit, when we modify the value of b, the value of a is also modified at the same time. Will not achieve the purpose we previously envisioned.

In [41]: a = [0, 1, 2]   # a为一个列表
         b = a   # 因为不想改变a的值,所以使用b复制a的值进行修改
         print("a的内存地址是:{},b的内存地址是:{},身份运算b is a的结果为:{}。".format(id(a), id(b), b is a))
Out[41]: a的内存地址是:2269977123784,b的内存地址是:2269977123784,身份运算b is a的结果为:True。
In [42]: b.append(3)   # 给b增加一个元素3,append()是给列表增加元素的函数,后面会讲
         print("因为内存地址相同,所以b的值修改为:{}时,a的值也同样被修改为:{}。".format(a, b))
Out[42]: 因为内存地址相同,所以b的值修改为:[0, 1, 2, 3]时,a的值也同样被修改为:[0, 1, 2, 3]。

Therefore, in future studies, everyone should pay special attention to this point. As for how to copy to be able to modify the value of the original variable at the same time as we imagined, we will introduce it later when needed.

7, bit operation

Bit operations are operations performed on binary numbers. Not only is the algorithm a bit tedious, the most important thing is that we don't use it. Therefore, only a few bit operations are listed here for your reference. Let me give you two examples to experience them.

Operator

description

Instance

&

Bitwise AND operator: the two values ​​involved in the operation, if the two corresponding bits are both 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 two corresponding 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 result 49, binary interpretation: 0011 0001

~

Bitwise inversion operator: Invert each binary bit of the data, that is, change 1 to 0 and 0 to 1. ~x is similar to -x-1

(~a) Output result -61, binary interpretation: 1100 0011, in the complement form of a signed binary number.

<<

Left shift operator: all binary bits of the operand are shifted to the left by a number of bits. The number to the right of "<<" specifies the number of bits to move, the high bits are discarded, and the low bits are 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 several bits, and the number on the right of ">>" specifies the number of bits to move

a >> 2 Output result 15, binary interpretation: 0000 1111

In the example in the above table, the value of a is 0011 1100, and the value of b is 0000 1101.

What if the result of a & b is calculated? To break it down, the numbers at the corresponding positions of a and b do the logical operation “and” mentioned above, where 0 represents False and 1 represents True. Combination 01 and combination 10 both get 0, and only combination 11 gets 1. The picture below will make it clearer:

 

To give another example, a >> 2 is to move the number on each of a to the right by two positions, and the number at the end is moved to the front accordingly.

The calculation process of other bit operations is left for everyone to explore. If it is not easy to understand, just like the above example, just calculate one by one according to the rules.

The above are all the types of operations in Python. Finally, let's take a look at the priority of these operations. The priority of arithmetic operations is the same as in our mathematics, just remember the priority of a few special types of operations. Operations within the same priority are calculated in the order from left to right appearing in the formula, and those in parentheses are calculated first. These rules are also the same.

Operator

description

**

Index (highest priority)

~ + -

Bitwise flip, unary plus and minus signs (the last two methods are named +@ and -@)

* / % //

Multiply, divide, modulo and divide

+ -

Addition and subtraction

>> <<

Shift right, shift left operator

&

Bit'AND'

^ |

Bit operator

<= < > >=

Comparison operator

<> == !=

Equal operator

= %= /= //= -= += *= **=

Assignment operator

is is not

Identity operator

in not in

Member operator

not and or

Logical Operators

At this point, the operation of Python is also explained. In the following chapters, we will break through the order of strings, lists, dictionaries, tuples, and sets in traditional tutorials, put the introduction of control flow statements to the front, and combine the content of strings, numbers, and operations mentioned earlier. , We can start writing our own small programs, so stay tuned.

 

 


Thanks for reading this article! If you have any questions, please leave a message and discuss together ^_^

Welcome to scan the QR code below, follow the "Yesu Python" public account, read other articles in the "Learning Python with You Hand in Hand" series, or click the link below to go directly.

"Learning Python with You Hand in Hand" 1-Why learn Python?

"Learning Python with you hand in hand" 2-Python installation

"Learning Python with You Hand in Hand" 3-PyCharm installation and configuration

"Learning Python with You Hand in Hand" 4-Hello World!

"Learning Python with You Hand in Hand" 5-Jupyter Notebook

"Learning Python with You Hand in Hand" 6-String Identification

"Learning Python with You Hand in Hand" 7-Index of Strings

"Learning Python with You Hand in Hand" 8-String Slicing

"Learning Python with You Hand in Hand" 9-String Operations

"Learning Python with You Hand in Hand" 10-String Functions

"Learning Python with You Hand in Hand" 11-Formatted Output of Strings

"Learning Python with You Hand in Hand" 12-Numbers

For Fans: Follow the "also said Python" public account, reply "hand 13", you can download the sample sentences used in this article for free.

Also talk about Python-a learning and sharing area for Python lovers

 

Guess you like

Origin blog.csdn.net/mnpy2019/article/details/98847561