python basics

1. The print() function
The print function is used to output what you want to the console, python interpreter, and cmd command line. The print function has input parameters, which can be strings, numbers, variables, etc., or a mixture of them. Different objects can be separated by , and when the print function encounters , it will output a space as a separated output. Effect. Note: In the print function, if the input content can continue to be calculated or merged, then python will first calculate or merge before outputting.
For example:
print(100+200)
print('a'+'b')
will output the number 300 and the string 'ab'

2. The input() function is
used to obtain user input from the command line and the python interpreter, and from the subline text cannot be entered. All user input will be treated as str type, that is, string type, the user can put the input content into the variable, that is: name=input() is used to save the input content as a reference to the subsequent code. At the same time, for a more friendly interface, you can input parameter values ​​to the input function. The parameter value can be a string or a variable reference, which is used to give a detailed description when prompting the user for input, namely: name =input('inpurt your name:') or i='please input here:' , name=input(variable i).

3. Organization The way
of organization of python is through unified indentation, and the theme is concise and elegant.

4. Data types and variables
==== Integers and floating-point numbers:
Integers are divided into positive integers, negative integers, and 0
floating-point numbers have precision problems. Large floating-point numbers can be marked with scientific notation, where 10 is represented by e , ie: 12300000 = 1.23e7 , or something like 2.35e-5 etc.
==== String:
String, as the name suggests, is a sequence of characters, enclosed in single or double quotation marks, and the surrounding single or double quotation marks are not counted as the content of the string.
If there are single quotes in the string content, it should be surrounded by double quotes, and vice versa, if there are both single quotes and double quotes in the string content, use \ to escape one of the quotes,
such as: ' i\' am a "good" man ' , use \' to represent escape single quotes
==== string + escape character:
In the print function, the carriage return cannot be used to reflect the newline of the final printed string, you must use \n to Indicates a newline, use \t to indicate a tab, \single or double quotation marks, \\ indicates a \ symbol
Note: By default, the \ escape character in a string will be escaped, and the escape rules are as described above. . But if you add r in front of the string, it means that the content of the string will not be escaped
. For example:
default escape, print('line1\'line2')---->line1'line2 is
forced not to escape, print(r 'line1\'line2')----->line1\'line2 (can be used in the filter rule of re) In
this case, it will not be escaped: print('line1\\'+'nline2')-- ---->line1\nline2
====string +'''''' to simplify line breaks:
If you want to output a paragraph, involving multiple line breaks inside the string, you can use \n to achieve, or you can use print(''' '''





''')
==== Boolean value:
True and False, used for various judgments, meaning that an event is true or false, such as 3>2 is true, 2==0 is false
logical operation and, or , not, the logical operation will be calculated in combination with the boolean value, such as the result of True and True is True
 
Note: In python, 1 can be considered as True, 0 is considered as False (can be calculated), other values ​​are neither True nor False
Note that is means that both sides are the same object
==== null value:
The null value in python is represented by None, note that None is not 0, it is meaningful for 0, and None is a special attribute, Means empty
==== variable:
python supports a variety of data types, including built-in native data types, and custom extended data types. Any type of data can be regarded as an object, which can be pointed to by variables and assigned to variables It is to let a variable point to a certain object and establish a relationship between them.
A variable is like a pointer, pointing to a certain memory object. Python is a dynamic language, so it can point to objects of different types, such as str, int, float, list, etc. Java is a static language. Once int a, then a can only point to ini type Object
a='hello' , b=a , means to assign the address of the object pointed to by a to b, or let b point to the object pointed to by a. At this time, the 'hello' object has two pointers pointing to itself. If a='world' at this time, then print(b) is still equal to 'hello'




Use % to get the remainder

5, string encoding problem
==== History:
In the history of computers, computers were designed to have the function of processing numbers, and 1 byte at the bottom of the computer is defined as 8 bits, which can be represented by 1 byte The maximum number is 255. If you need to represent a larger number, you need more bytes. 2 bytes can represent a maximum of 65535, and 4 bytes can represent about 4.2 billion. According to the original design of the computer, only numbers can be processed. If you want to process text, that is, to process strings, you need to map strings with numbers, that is, to record the numbers corresponding to each character by encoding. The computer was invented by Americans, so it only needed to process English strings at that time. All English characters, including uppercase and lowercase letters, numbers, symbols, etc., were added together to form a total of 127 characters. can be fully expressed. By mapping an integer corresponding to 1 byte to different characters, this encoding method is the ASCII encoding method.
With the development of computers, different countries are using them, and they all want to input their own languages ​​through computers, such as Chinese. For Chinese, Chinese characters need at least 2 bytes, that is, at least 65535 numbers to be represented, so China is Chinese has customized the GB2312 encoding method, which is used to encode Chinese to the underlying integer of the computer. Similarly, different countries have different encoding methods, which leads to: the same encoded integer may have different representations in different countries, and if programs from multiple countries are put together, the computer cannot recognize a certain character. Whether the string belongs to English or Chinese or other country characters.
In order to solve the problem of customizing different encoding standards in different countries, the unicode unified character encoding standard has emerged. The unicode standard often uses 2 bytes to represent 1 character, and all languages ​​in the world are included in this encoding standard, so no matter where the computer is. Use, no matter what language the computer uses, there will be no confusion and conflict problems. For some rare characters, unicode may need to use 4-6 characters to represent.
If only unicode encoding is used, there will be a problem of wasting space. If the program is written in English, all English characters default to 2 unicode bytes corresponding to 1 English character. Therefore, although the use of unicode can solve the problem of intercommunication between different languages, it will bring about waste of space and low efficiency.
At this time, the UTF-8 variable length encoding method needs to be used. When using UTF-8, if it is Chinese, 2 bytes correspond to 1 Chinese character, and if it is English, 1 byte corresponds to 1 English character, that is, The number of bytes used in UTF-8 is flexible according to the actual language used, and this benefit is especially reflected in data storage, compression, and transmission. Therefore, the data saved by the current computer are all encoded in UTF-8. Once called by the program, the data in the file is converted into unicode encoding and processed in the memory, and is converted into high-efficiency before being saved again after processing. UTF-8 encoding method.
When we get a webpage from a website, the html of the webpage is sent back to our browser in the form of source code. The source code often contains: <meta charset="utf-8" /> means that the webpage uses UTF-8 encoding way to transmit data.
====Encoding of python strings: In the
python3 version, all string str type objects use unicode encoding, that is, all strings in python have corresponding unicode integers, such as:
 
unicode is for each If the character is encoded, you can use the ord() function to find the corresponding unicode integer for any character, or you can input the unicode integer through chr() to get the corresponding unicode character
. Of course, you can also write like this: '\uxxxx' Put the hexadecimal number of the unicode integer, for example, the hexadecimal number of 25991 is 0x6587:
 
==== encoding conversion:
Python's data in memory are all unicode encoded and are all objects of type str. When data is stored or transmitted over the network, it must be converted into a byte stream of byte type. Converting unicode to byte type requires different encodings according to different contents. All byte type objects start with b, such as:
'abc' is an object of str type, it is unicode encoding, and it is English, so the conversion into a transportable byte stream is 'abc'.encode('ascii')---->b'abc', at this time ascii encoding , 1 byte corresponds to 1 English character
'Chinese' is an object of str type, it is unicode encoding, it is Chinese, so the byte stream converted to transmittable is 'Chinese'.encode('utf-8')- --->b'\xe4\xb8\xad\xe6\x96\x87', at this time, in utf-8 encoding, 3 bytes are used to represent 1 Chinese character
------------ -------------------------------------------------- ----------------------------------------'Chinese'.encode('gb2312') ---->b'\xd6\xd0\xce\xc4'
, at this time, in the gb2312 encoding, 2 characters are used to represent 1 Chinese character . Summary: In the computer memory, in python3, all str objects are unicode encoding, which is to enable the languages ​​of different countries to communicate with each other, and the unicode encoding is generally 2 A byte encodes 1 character. When transmitting and saving data, it is necessary to convert unicode-encoded characters into other encoding methods. English can be converted into ascii or utf-8, and Chinese can be converted into gb2312 or utf-8, which becomes a transmittable byte stream. . With different encodings, 1 character uses a different number of bytes.
In general, we use both unicode and utf-8, because both Chinese and English can be encoded in utf-8. which is:
The str object.encode('utf-8') can be turned into a byte stream byte type object starting with b, and the    
byte object.decode('utf-8') can be turned into a str type object of unicode characters for use in computers and programs processing,
so at the beginning of the hello.py file there are: #coding:utf-8 is to tell the python interpreter: use utf-8 encoding to decode to unicode for processing, and then encode the unicode data to utf-8 to save And the format string of transmission
====python:
last=72
today=85
rate=(today-last)/last
print('Xiao Ming's grade has increased from last year's %d points to this year's %d points, an increase in percentage Yes: %.1f%%' %(last,today,rate))

6. Properties of list and tuple
====list:
list is python's built-in data type, translated into lists or arrays. A list is a sequence of data or a set of objects or a set of elements, and different arrangements of the same elements are different lists. The number of elements in the list can be obtained by len(a). list is a variable-length array. You can add elements at the end by appending at any time. By pop(i), the element at position i is popped at the end by default. By insert(i,xx) Insert xx element at position i. In addition, list is also a mixed-type array, that is, elements of different types can be allowed inside the array, such as: a=[1,True,'abc',2.2], at this time a is a variable pointing to a list address ( are pointers in nature). The list gets each element by subscripting the range of 0~len-1. The list can get elements from the tail through -1, -2, -1 means the first element from the bottom, -2 means the second element from the bottom, and so on. Any type of object can be placed in the list, in addition to Python's built-in integers, floating-point numbers, Boolean values, strings, etc., it can also be list, tuple, dict, other custom data types, and so on. If there is another list in the list, it means that the inner list is a two-dimensional array. If an object of the inner list is still a list, the innermost list is a three-dimensional array, and so on, through a[1][2] to get the elements of a two-dimensional array.
====The nature of
tuple: The nature of tuple is very similar to that of list. The biggest difference is that tuple is stricter and safer, and data can only be taken and cannot be added, deleted or modified. That is, once the tuple is initialized, the content cannot be changed, while the list can be added or deleted at any time. element.
==== Note: Ambiguous tuple notation:
When creating a list, use [], when creating a tuple, use (), if you create an empty list, it is a=[], if you create an empty tuple, it is a=(), if you create one, it contains only 1 The tuple of elements should not be written as a=(1), which will be interpreted by python as a=1, a is an object of type int because python has ambiguity when it encounters (), is it a tuple or ordinary parentheses , Python stipulates that it is used as parentheses, so declaring a tuple with only 1 element should be: a=(1,) Be careful not to lack the comma.
====Note: "Variable" tuple The
immutability of tuple means that the address of the object pointed to by each element in the tuple does not change, but the content of the pointed object can be changed, such as:
a= ('a','b',['A','B'])
a[2][0]='X'
a[2][1]='Y'
print(a) --> (' a','b',['X','Y'
]) This modification is legal, because for tuple a, the element address of a[2] has not changed, that is, it does not point to other lists, and the content of the list with unchanged address changes does not affect The tuple's provisions.

7. Conditional judgment
if, elif, else judgment statement, used for branch judgment, if can be understood as judging whether the following statement is true, if it is true, execute the if statement block, if it is not true, it must be false, then execute else Statement block, use elif to add multiple judgment conditions. The judgment logic of using multiple if and elif together is similar to the ACL access control list. The judgment order is also from top to bottom. If one judgment condition is not satisfied, it will be extended to the next judgment condition. Once a judgment condition is true, no subsequent judgment will be performed. If all if and elif are judged to be false, use the last else as the meaning of permit any.
Be careful not to omit the colon after the conditional judgment. The conditional judgment can also be abbreviated as if x: As long as this x is a non-zero integer, non-empty list, non-empty tuple, non-empty string, etc., it is considered to be True, otherwise it is considered to be False.
The input() function is used to obtain user input, whether the user input is a number, character, or string, etc., it is returned by the input function in the type of str.
You can get the value of a string through the eval() function, such as: '2' is 2, 'a' will get the variable a

8.
Loops There are two types of loops in python
====for loops:
for loops are used to traverse A sequence that assigns each element in the sequence to a custom variable to manipulate all element values ​​in the sequence, such as:
 
Note: generally use list(range(10)) to construct a list of 10 elements, because from 0 starts so it is 10 elements from 0 to 9.
The loop execution of the for loop depends on the explicit range traversal (cannot rely on the conditional judgment)
====while loop:
The execution of the while loop depends on the conditional judgment after the while keyword. When it is true, the loop body is executed, and after the execution is completed Conditional judgment again, jump out of the loop when it is false, so the loop body needs to have certain restrictions or means to ensure that it can jump out after a limited number of loops, that is, the execution of the while loop depends on the condition judgment + the internal restrictions of the loop body
Note: When jumping out of the while loop, it must be the first time that the judgment of the loop condition is not satisfied
====break:
Use break inside the loop body to jump out of the current layer of loop, which is used for special and necessary program execution branch flow
== ==continue:
Use continue inside the loop body to omit the remaining loop body statements and start the next loop immediately. If it is for, it will interrupt and traverse the next element in advance. If it is while, it will interrupt and execute the next conditional judgment in advance
. The planned use of break and continue will indeed lead to confusion in the logic and execution flow of the program, increasing the complexity of the code and the workload of later debugging.
In addition, just like infinite iteration will cause the machine to crash, the infinite loop will also cause the machine to crash, so the first thing to pay attention to when writing a loop is whether it can jump out of the loop body when necessary, especially whether there are enough constraints and conditions in the while loop body. means.

9. dict and set
are very similar to list and tuple, and they are both built-in data types of python. Dict and set are also built-in data types of python, and they are very similar.
====dict:
dict is called a dictionary in python. It is a key-value pair. unique mapping. The dict is represented by {}, and each key-value pair is filled in with commas. The key in the dict is the input or keyword in the hash table. The dict uses the hash algorithm to map the key to a unique memory address. The memory address can store other objects, that is, the value, so the key is required to be immutable (that is, once initialized That is, it cannot be changed again), such as integers, strings, tuple, etc., while the value of value is variable, but if the value changes multiple times, the last value will prevail. In dict, keys are not sorted, that is, you cannot use dict[0] to obtain the first element in a similar way to list and tuple, and dict can only use the form of d[key name] to obtain the corresponding key value.
dict uses the method of d[key name]=value to add a key-value pair to a dict, you can also use the method of del d[key] to delete a key-value pair, or use the method of d.pop(key) to pop up a key Value pair, dict uses d[key name] to access the value corresponding to this key. If there is no such key, an error will be reported, so the access method can also be: key in d Use Boolean to determine whether it contains this key, or d. get(key,-1) gets the value of the key of d. If there is no key, it returns -1. By default, it returns None and cannot display the result in the python interpreter.
If you encounter any two objects that are related, you can make one a key and the other a value and put it in the dict. The search speed in the dict is very fast and basically equal to O(1).
====set:
set is called a set in python, more precisely, it is a collection of non-repeating objects. The reason why it is not a sequence is because set is unordered, that is, s[0] cannot be used. This sequential access method to access, just like dict, is also unordered.
At the same time, the construction of set is represented by {}, which is the same as dict, but the object of set is not a key-value pair like dict. In fact, the object of set has only key and no value.
You can use the s=set(a sequence) function to construct a set. The input needs to be a sequence, which can be list, tuple, range(10), etc.
The most important features of
set are: 1. There is no repetition of objects in the set.
2. As a set, set can be used for mathematical set operations, such as intersection &, union |
intersection: take the common part of s1 and s2 as the result, that is, the intersection is a subset of s1 and also a subset union of s2
: integrate all elements of s1 and s2 and eliminate duplicates, that is, s1 is a subset of the union, and s2 pages are a subset of the union
3. Set can increase or decrease objects, s.add(100), s.remove(2) If multiple duplicate objects are added, set will automatically filter
==== Note:
Regarding immutable objects: First, objects cannot be Change means that once an object is constructed and initialized, the address of the object and the value of the object cannot be changed, such as: integer, string, tuple, dict key, etc. Secondly, if some functions of immutable objects involve changing the value of the object, they will generally copy an object of the same value and return, but the original immutable object still does not change the value, so as to ensure the immutability of the object. For mutable objects, if the function of the object involves changing the value of the object, it is directly changed on the original object. For example:
because str1 is immutable, another object is returned when replace involves modifying the value.
Because list1 is variable, the value is directly modified on the list1 object, and another object is not returned.
 




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325071380&siteId=291194637