Python review one

Python review 1

variable##

Variables in Python are written similarly to variables in C;

Writing requirements##

Python program writing structure uses indentation, discarding curly braces;

structure##

Branch:

if(Conditional statement 1):
Execute statement block
elseif(Conditional statement 2):
 Execute statement block
else:
 Execute statement block

Loop:

while loop####

while loop condition:
Loop statement body

for loop####

for target in expression:
Loop statement body

The result of the expression will be combined with the target

Step function
range(x,y,z)
​ x: Start
​ y: end (y-1)
​ z: step size

Jump out of the current structure

End the operation of this loop body

List##

Create list

>>> num =[1,2,3,4,5]//List creation>>> num				  //List output[1,2,3,4,5]>>> num =['Hello','Hello there',666]>>> num //The list supports various types, and all characters except numbers need to use single quotes['Hello','Hello there',666]

append(): add element####

>>> num.append(6)>>> num
[1,2,3,4,5,6]

extend(): add multiple elements####

>>> num.extend([7,8,9])>>> num
[1,2,3,4,5,6,7,8,9]

append() is to add a single element, which is a simple expansion;
And extend() is to splice the original list and the list you want to add into a new list

insert(): Insert an element in the list####

>>> num.insert(0,0)//Add element 0 at index 0>>> num
[0,1,2,3,4,5,6,7,8,9]

pop(): delete list element####

>>> num.pop()9>>> num.pop(0)0>>> num
[1,2,3,4,5,6,7,8]

del statement: delete list

>>> num =[1,2,3,4,5,6,7,8]>>> num
[1,2,3,4,5,6,7,8]>>> del num[7]>>> num
[1,2,3,4,5,6,7]>>> del num
>>> num
Traceback(most recent call last):
 File "<pyshell#19>", line 1,in<module>
 num
NameError: name 'num' is not defined

If an error is reported: num does not exist

remove(): delete known X elements

Our previous del statement and pop() function rely on the index of the list to delete the elements under the index, and remove() does not rely on the index, but deletes according to the specific content of the element.

>>> num =['Hello','Hello there',666]>>> num
[' Hello','Hello there',666]>>> num.remove(666)>>> num
[' Hello','Hello there']>>> num.remove('Hello there')>>> num
[' Hello']

List fragmentation###

To output or display or copy only a part of the data elements of a list is the so-called list fragmentation

>>> num =['HUAWEI',"CHINA",'Mirror','XIAOMI']>>> num
[' HUAWEI','CHINA','Mirror','XIAOMI']>>> num[0:1]['HUAWEI']>>> num[0:2]['HUAWEI','CHINA']>>> num[0:4]['HUAWEI','CHINA','Mirror','XIAOMI']>>> num[:2]['HUAWEI','CHINA']>>> num[:]['HUAWEI','CHINA','Mirror','XIAOMI']>>> num[2:]['Mirror','XIAOMI']

Observe carefully and find that the sliced [x:y] is the range of left-closed and right-opened (principle) [Many closed problems related to the range in python are the principle of left-closed and right-opened]
At the same time, the fragmentation mechanism also supports the omission of range values; that is, if the left is empty, it will start from 0, if the right is empty, it will end at the last element, and if both left and right are empty, all elements will be output;

Advanced Sharding

Everyone thinks that fragmentation has only two parameters?
Sharding has three parameters ==> [x:y:z]
​ x: Start
​ y: end
​ z: Step length (that is, the number of increments is z, which can also be understood as the concept of arithmetic in mathematics)

>>> num =[]//Create an empty array>>>for i inrange(1,10):
	num.append(i)>>> num
[1,2,3,4,5,6,7,8,9]>>> num[0:10:2][1,3,5,7,9]

Initial discussion of depth copy####

>>> list =[1,2,3,4]>>> copy = list
>>> copy1 = list
>>> copy2 = list[:]>>> copy1
[1,2,3,4]>>> copy2
[1,2,3,4]

It can be seen from the above that the result of direct copying of list is the same as that of list[:] fragmented copying, but in fact it is secretly impatient!

>>> list.append(5)>>> copy1
[1,2,3,4,5]>>> copy2
[1,2,3,4]

Add an element to the original source list append() and find that the contents of copy1 and the list source list are not changed together (append() operation)

copy1 = list: belongs to the memory address of the list to copy1,
copy2 = list[:]: belongs to the value of list to copy2

List comparison###

The list supports comparison operations of comparison operators:

>>> list1 =[123]>>> list2 =[234]>>> list3 =[123]>>> list1 < list2
True
>>> list1 <= list3
True
>>> list1 == list3
True
>>> list1 != list2
True
>>> list1.append(234)>>> list2.append(123)>>> list1
[123,234]>>> list2
[234,123]>>> list1 > list2
False

The comparison of two lists is based on the size of the ASCII value. If two elements are encountered, the first is compared, and if the first is the same, the second is compared.

String list###

Stitching and repetition

>>> str1
[' HUAWEI']>>> str2
[' CHINA']>>> str1 + str2
[' HUAWEI','CHINA']>>> str1 *3['HUAWEI','HUAWEI','HUAWEI']>>> str1 = str1 +str2
>>> str1
[' HUAWEI','CHINA']>>> str1[1]*3'CHINACHINACHINA'

Element judgment: in/not in

>>> str1
[' HUAWEI','CHINA']>>>"CHINA"in str1
True
>>>" CHINA" not in str1
False

Element query###

index(): the index of the query element####

>>> str =["H","U","A","W","E","I"]>>> str
[' H','U','A','W','E','I']>>> str.index("I")5>>> str.index("K")//Element does not exist save Traceback(most recent call last):
 File "<pyshell#4>", line 1,in<module>
 str.index("K")
ValueError:'K' is not in list
>>>

count(): the number of repetitions of the query element####

>>> list
[3,4,5,2,5,66,7,2,5,7]>>> list.count(5)3

Sorting: reverse(), sort()

>>> list
[3,4,5,2,5,66,7,2,5,7]>>> list.reverse()//Reverse arrangement>>> list
[7,5,2,7,66,5,2,5,4,3]>>> list.sort()//Ascending>>> list
[2,2,3,4,5,5,5,7,7,66]>>> list.reverse()//Reverse arrangement (srot+reverse ==>Descending)>>> list
[66,7,7,5,5,5,4,3,2,2]

Tuple##

A tuple can be understood as a list that cannot be changed once defined.

Tuple creation

>>> tuple =(1,2,3,4,5)>>> number =[1,2,3,4,5]>>>tuple(1,2,3,4,5)>>> number
[1,2,3,4,5]

Tuple is a tuple, number is a list;

Can be found; the definitions of the two are different

A tuple is a set of list data composed of parentheses, and a list is a set of data composed of square brackets

Tuple access###

The access method of a tuple is the same as that of a list. The elements of a tuple are mainly accessed through the index of the tuple. Like a list, it can be accessed through sharding (slicing).

>>> tuple(1,2,3,4,5)>>> tuple[2]3>>> tuple[3]4>>> tuple[:](1,2,3,4,5)

type() method

>>> tup =()>>> num =[]>>>type(tup)<class'tuple'>>>>type(num)<class'list'>

Many times, the list data defined by parentheses is considered to be a tuple, but it is not!

>>> del tup
>>> tup
Traceback(most recent call last):
 File "<pyshell#14>", line 1,in<module>
 tup
NameError: name 'tup' is not defined
>>> tup =1,2,3,4>>>type(tup)<class'tuple'>

That's right, the list data without parentheses is also a tuple.

The characteristics of defining tuples are: comma

>>>(6)*636>>>(6,)*6(6,6,6,6,6,6)

So when defining a tuple, a comma is needed to tell the program that this is a tuple

>>> tup =(1,2,3,)>>>type(tup)<class'tuple'>

This is the most standard definition method. Why?

Tuple Update and Delete###

The functions of tuples and lists are almost the same except for data changes. The data of a tuple cannot be changed, but tuples and tuples can be spliced

>>> tup(1,2,3)>>> tup = tup[:3]+4,+5,Traceback(most recent call last):
 File "<pyshell#28>", line 1,in<module>
 tup = tup[:3]+4,+5,
TypeError: can only concatenate tuple(not "int") to tuple
>>> tup = tup[:3]+(4,)+(5,6,)>>>tup(1,2,3,4,5,6)

tup uses splicing to update the tup tuple data;

note:

​ Here when splicing, the content of the splicing is marked with brackets and commas to indicate that this is a tuple data, otherwise it will be regarded as a character or numeric data by the program.

The comma is the symbol definition of a tuple

>>> tup = tup[:2]+ tup[4:]>>>tup(1,2,5,6)

The elements that need to be deleted are covered by the splicing method to achieve the purpose of deleting the elements.

The data of tuples is unchanged, but tuples can be spliced freely like lists:

​ Use the slice at the end to add elements to the element (note the comma mark of the tuple element)

​ Use the method of slicing and splicing to cut and delete the content before and after the element is spliced ​​into a new tuple

String##

create###

>>> char ="HUAWEI">>> str ='XIAOMI'>>> char
' HUAWEI'>>> str
' XIAOMI'

Single and double quotes can be used to create strings

String modification

>>> str = str[:3]+"-"+ str[3:]>>> str
' XIA-OMI'

The modification of a string is similar to a tuple, and the content of the string is changed by means of slicing and splicing.

ps: It is to reconstitute a new string to a new string variable, so it needs to be assigned

String formatting###

format()

>>>'{0}- {1}={2}'. format('XIAOMI','HUAWEI','CHINA')'XIAOMI-HUAWEI=CHINA'

As can be seen from the code, the content of the curly brackets in the string is the parameter value index content corresponding to the format method. In layman's terms: the index in the curly brackets will call the corresponding parameter value in the format to form a string. {The parameter in format is called: positional parameter}

>>>'{ x}-{h}={c}'.format(x='XIAOMI',h='HUAWEI',c='CHINA')'XIAOMI-HUAWEI=CHINA'

Format operation##

Format operator

Format symbol Description
%c formatting characters and ASCII
%s format string
%d formatted integer (decimal)
%o Format unsigned octal
%x 、%X format unsigned hexadecimal (lowercase, uppercase)
%f Format floating point numbers
%e 、%E format the floating point number in scientific notation

The above is a common format symbol operation; it is similar to the C language.

Formatting operation writing###

'[ Format operator]'%[Content that needs to be formatted]
>>>' %c'%99'c'

The formatting operation is expressed as: percent sign ==> %

Auxiliary parameters###

Parameter command Description
mn m is the minimum width, n is the number of digits after the decimal point
- Align Left
+ Show plus before the certificate
# Displayed in octal and decimal results respectively: 0o and 0x/0X
0 Fill the space with "0" before the number
Escape character description
\ ' Single quote
\ " Double quotes
\ a System beeps
\ b Backspace
\ n newline
\ t, \v tab character (8 spaces)
\ f Form feed
\ r Carriage Return
\ | Backslash
\ 0 Represents a null character

sequence##

list(): Convert iterable object to list###

>>> list =list((1,2,3,4))>>> list
[1,2,3,4]>>> list =list("HUAWEI")>>> list
[' H','U','A','W','E','I']

tuple(): Convert iterable objects to tuples###

>>> tuple =tuple("HUAWEI")>>>tuple('H','U','A','W','E','I')>>>type(tuple)<class'tuple'>

str(): Convert obj object to string

>>> s =str(1)>>> s
'1'>>> type(s)<class'str'>>>>tuple(s)('1',)

len(sub): return parameter length###

>>> num =[1,2,3,5,6,7]>>>len(num)6

max()/min(): sequence maximum/minimum###

>>> num =[1,2,3,5,6,7]>>>len(num)6>>>max(num)7>>>min(num)1

sum(): return the sum

>>> num =[1,2,3,5,6,7]>>>sum(num)24

sorted(): sort###

>>> num
[12,24,33,32,243,3,6,23,15,7,6,5,3,2,1]>>> sorted(num)[1,2,3,3,5,6,6,7,12,15,23,24,32,33,243]>>> num
[12,24,33,32,243,3,6,23,15,7,6,5,3,2,1]>>> num.sort()>>> num
[1,2,3,3,5,6,6,7,12,15,23,24,32,33,243]

In the code, we compared with the previous sort() and found

​ sorted(): returns the result in ascending order but does not change the original data

​ sort(): sort the source list in ascending order

reversed(): Reverse iteration###

>>> list =list((2,4,67,3,7,3,8))>>>for i inreversed(list):print(i,end='-')8-3-7-3-67-4-2-

It can be seen that the reversed() method will output an iterable sequence in reverse iteration

enumerate(): Generate two tuples###

Two-tuple: A tuple with an element of 2 constitutes an iteration object, and each two-tuple is composed of the index of the iteration parameter and the corresponding element.

>>> for i inenumerate(list):print(i)(0,'H')(1,'U')(2,'A')(3,'W')(4,'E')(5,'I')

zip(): The iteration parameters are combined into a tuple###

Return a tuple of iterable parameters

>>> list
[2,4,67,3,7,3,8]>>> str
[' H','U','A','W','E','I']>>>for i inzip(list,str):print(i)(2,'H')(4,'U')(67,'A')(3,'W')(7,'E')(3,'I')

function##

Function creation and calling###

The meaning of the function is to encapsulate the required and repeated function code in an object function, which can be called directly when needed.

def out():print("Hello,World!")print("I am Mirror")out()//Call out function
Hello,World!
I am Mirror

Function parameters###

When the function is defined, you can add parameter settings in parentheses to set the parameters for the function. When calling the function, you will be required to pass in the parameters. The function body can also use this parameter value for work.

def name(s):print(s)

def sum(x,y):print(x+y)name("Mirror")sum(1,2)================ RESTART ================
Mirror
3

The function can receive zero or more parameter values. When the function is defined, the data type of the parameter can be undefined

Function return value###

def name(s):return"I am {0}".format(s)

def sum(x,y):return"SUM = {0}".format(x+y)print(name("Mirror"))print(sum(1,2))================ RESTART================
I am Mirror
SUM =3

Flexible functions###

Formal parameters and actual parameters####

From the parameters of the above example, the parameter setting and passing are recognized, but what if we don’t know how many data parameters we pass?

Function documentation####

Under normal circumstances, the triple quotation marks at the beginning of the quotation mark will not be printed out, but it will still be stored, which is very similar to the function of the comment. We can get the content in the triple quotation when calling to understand the function of the function

_ _ doc _ _: Get function
def sum(x,y):"""Return x,the sum of y"""return"SUM = {0}".format(x+y)print(sum.__doc__)================ RESTART ================
 Return x,the sum of y

Keyword function####

def sum(x,y):"""Return x,the sum of y"""return"SUM = {0}".format(x+y)print(sum(x=1,y=2))

Use the name of the formal parameter as a keyword, and use the "assignment" mode to pass the actual parameter to the specified parameter

Default parameters####

def sum(x=1,y=2):"""Return x,the sum of y"""return"SUM = {0}".format(x+y)print(sum())

Default parameter: The function defines the parameter and sets a default parameter to the parameter at the same time. If the function is called when the actual parameter is received, the default parameter of the parameter is used to run

variable parameter####

Going back to the formal parameters raised about not knowing the passing parameters:

From the parameters of the above example, the parameter setting and passing are recognized, but what if we don’t know how many data parameters we pass?

At this time, we need to set a variable parameter (parameter):

def sum(* s):print(len(s))print(type(s))sum(1,2,3,4,5,6,7)================ RESTART ================7<class'tuple'>

Observation and analysis show that: the formal parameter represented by the asterisk will automatically compress the received actual parameter sequence into a "tuple", we can only pass a single (number, character, string) parameter when no variable parameter is used

Dictionary collection##

Dictionary creation (dict)

>>> dict ={1:10086,"a":"CHINA"}>>> dict
{1:10086,' a':'CHINA'}>>> dict[1]//According to Key index and return Value10086>>> dict["a"]'CHINA'

The signature feature of a dictionary is: a sequence of key-value pairs surrounded by curly braces

Dictionary built-in operations###

formkeys(): Create and return a new dictionary####

>>> del dict
>>> dict.fromkeys((1,2,3)){1: None,2: None,3: None}

Return to dictionary content####

keys(): Return all key values of the dictionary#####
>>> dict
{1: None,2: None,3: None}>>> dict.keys()dict_keys([1,2,3])
values(): Return all Value values of the dictionary#####
>>> dict.values()dict_values([None, None, None])
items(): Return all items in the dictionary#####
>>> dict.items()dict_items([(1, None),(2, None),(3, None)])

get(): Query the value of a key

>>> dict
{1:10086,' a':'CHINA'}>>> dict.get("a")'CHINA'>>> dict.get(1)10086>>> dict.get("CHINA")>>> dict.get(112)

get() queries a key, if it does not exist, it will not return an error! You can use in/not in to determine whether it exists

claer(): Empty the dictionary####

>>> dict.clear()>>> dict
{}

ps: is to empty the content, not to delete

copy(): Copy the dictionary####

>>> dict
{1:10086,' a':'CHINA'}>>> c ={}//Define an empty dictionary>>> c
{}>>> type(c)<class'dict'>>>> c = dict.copy()>>> c
{1:10086,' a':'CHINA'}

pop(): Pop up (delete) value

>>> dict ={1:10086,"a":"CHINA"}>>> dict.pop(1)10086>>> dict
{' a':'CHINA'}>>> dict ={1:10086,"a":"CHINA"}>>> dict.popitem()('a','CHINA')>>> dict
{1:10086}

update(): Update dictionary####

>>> dict.update({2:2019})>>> dict
{1:10086,' a':'CHINA',2:2019}

Set creation (set)

>>> dict1 ={}>>> dict2 ={1,2,3,4,5}//Collection creation>>>type(dict1)<class'dict'>>>>type(dict2)<class'set'>

The characteristics of the collection can be found by comparing the collection with the dictionary:

​ The set is a comma-separated sequence using curly braces but not applicable key-value pairs

>>> set={1,2,3,4,5,6}

Visit collection

>>> set1
{1,2,3,4,5,6}>>> for i in set1:print(i,end=" ")123456

Python file##

File open open()

Operator####

Logo Description
r Open the file as read-only
w Open file for writing
x If the file exists, an exception will be thrown
a Open for writing, existing files can be added
b Open file in binary
t Open as text
+ Read and write mode
U Universal newline support

open() function####

open(): used to create a file object so that other operations can use the file object

Operation function###

close(): close the file####

read(): Read characters

readline(): Read a line of string

write(): output content to the file####

writelines(): output sequence to file

seek(): Move the file pointer

tell(): Return the position of the current file####

OS file module###

os module; import os import os module

Directory operations

getcwd(): Get the current directory#####
chdir(): switch directory#####
listdir(): View the contents of any directory#####
mkdir(): Create a folder (directory)
makedirs(): Create multi-level folders (directories)

Delete operation

remove(): delete the specified file#####
radir(): Delete the specified folder (directory)
removedirs(): Remove multi-level folders (directories)
rename(): file/folder rename#####

System operation

system(): call tool
walk(): Traverse subdirectories and return triples

path path operation

path.basename(): Get the file name#####
path.dirname(): Get the path name#####
path.join(): Full path join
path.split(): Separate path and file name#####
path.splitext(): separate file name and extension
path.getsize(): Get file size (bytes)

path time function####

path.getatime(): last access time#####
path.getctime(): Creation time#####
path.getmtime(): Modification time#####

prckle() module###

Objects can be stored on disk in the form of files; it is a simple persistence function

All data types of python can be serialized and stored on disk using prckle()

Exception handling##

AssertionError: Assertion###

When assert is testing the program, insert checkpoints in the code

>>> list =['Mirror']>>> assert len(list)>0>>> list.pop()'Mirror'>>> assert len(list)>0Traceback(most recent call last):
 File "<pyshell#3>", line 1,in<module>
 assert len(list)>0
AssertionError

Assert assertion: When the condition behind the statement is satisfied, the assert will not be compiled. If the assertion condition is satisfied, an error will be reported in the program.

As in the above code program: there is an element in the original list, and assert does not report an error, but after the pop method pops up (deletes) the element, an error will be reported if the assert condition is not met.

try-except statement###

try:
examination range
except exception[as e]:
How to deal with an exception after detection
finally://Optional
Code block
>>> try:
		file =open("a.txt")
		file.close()
	except OSError:print("Error")

	
Error

For example, the program in the example detects that an OSError error occurs when calling the file file object, and executes the error (abnormal) code execution block

>>> try:
 	file =open("a.txt")
 	file.close
	except OSError as e:print(str(e)+"Error")
	except TypeError as e:print(str(e)+"Error")[Errno 2] No such file or directory:'a.txt'Error

As above; use the as error method to write the error information into the e variable, and output the error information in the type of str; at the same time, it is found that a variety of different error types and error output can be defined.

abnormal####

Exception: the base class of all exceptions (can receive exceptions of any kind)

AssertionError: The assert statement failed (assert condition is not established)

AttributeError: Access an attribute that an object does not have (the object attribute does not exist)

IOError: Input and output operation is abnormal

ImportError: Cannot import module or package (path error, etc.)

IndexError: Index exceeds sequence boundary

KeyError: access key that does not exist in the dictionary

KeyboardInterrupt: Ctrl+C is triggered

NamError: The object used has no variables

SyntaxError: Code logic syntax error

TypeError: Object type and statement requirements do not match

UnboundLocalError: Global variable exception

ValueError: The value passed in is abnormal

ZeroDivisonError: Trigger division by zero exception

Third-party GUI module: EasyGUI

Classes and objects##

Understanding classes and objects###

Class: class Class name:

Object: def method name ():

A program can be composed of multiple classes, and a class is composed of multiple object methods;

Self keyword: object parameters representing oneself

There is only one difference between class methods and ordinary functions: they must have an additional parameter name, but you cannot assign a value to this parameter when calling this method. Python will provide this value. This special variable refers to the object itself, named: self;

Explore the Python magic method###

__ init__() construction method####

As long as an object is instantiated, this method will be automatically called before the object is created; the parameter parameters will also be automatically passed into the method; the method can be rewritten to achieve the initialization operation

classPotate:
 def __init__(self.name):
  self.name = name
 def kick(self):pirnt(self.name)

Public and private

public: public, public

private: private

The above are C++ and Java methods;

Represent private attributes in Python: the first two underscores "__" in the variable name

inherit##

class name(Inherited class):

Python supports multiple inheritance, that is, a class inherits multiple parent classes; [not recommended]

Recommended Posts

Python review one
Python classic interview question one​
Python multithreading
Python CookBook
Python FAQ
Python3 dictionary
Python3 module
python (you-get)
Python string
Python basics
Python descriptor
Python basics 2
Python exec
Python notes
Python3 tuple
CentOS + Python3.6+
Python advanced (1)
Python decorator
Python IO
Python multithreading
Python toolchain
Python3 list
Python multitasking-coroutine
Python overview
python introduction
Learn Python in one minute | Object-oriented (Chinese)
Python analytic
Python basics
07. Python3 functions
Learn Python in one minute | Python functions (on)
Python basics 3
Python multitasking-threads
Python functions
python sys.stdout
python operator
Python entry-3
Centos 7.5 python3.6
Python string
python queue Queue
Python basics 4
Python basics 5
Learn Python in One Minute | Object Oriented (Part 1)
One picture flow: all built-in exceptions in Python
One article to get regular expressions in Python