(1) I have to go to school. (2) I have to go to school. (3) I have to go to school


I have been in touch with python for a long time. The following is a complete review of the basic knowledge of python:

  1. two ways to avoid special characters such as’ \n’ :
a ) using the escape character ' \'
b ) using the original character ' r' print r'c:\now'
  1. single-line comments, using 1 #, such as:
#hello Python
 Multi-line comments are used 3 A single quotation mark (or 3 ), such as:
'''hello python
hello world'''
 or
"""hello python
hello world"""
 Also, strings that span multiple lines. You can also use 3 A single quote or 3 Double quotation marks, such as:
'''......'''
 or
"""......"""
  1. special symbols such as double quotation marks are embedded in the string
a ) using the escape character ' \'
b ) use single quotation marks around the string. print ('i l"o"ve fis.com')
  1. conditional branch:
if condition:
      An operation performed with the condition true
  else:
      An operation whose condition is false

  if condition:
     action
  elif condition:
     action
  else:
    action

python Can effectively avoid "hanging. else "( if else Correspondence error)
 Conditional expression ( 3 Meta operator)
    small = x if x<y else y
     if x<y ,small=x. Otherwise, small=y
 assertions assert : when the condition after the keyword is false, the program crashes and throws an exception
   assert 3>4
    You can use it to place checkpoints
  1. while conditions:
 An operation performed with the condition true

for  The target  in  Expressions:
 The loop body
  Ex. : favorite='fishc'
    for i in favorite:
       print(i,end='')

range([start,] stop[,step=1])
 generate 1 A from start The value of the parameter stop The numeric sequence of parameter values

break : terminates the current body of the loop. Jump to outer program
continue: Terminate the cycle and start 1 Cycle ( if condition true )
  1. the logical operator and can join any expression at 1 and get a Boolean value

  2. introduction of foreign aid:

a ) random The module
b ) randint(), return 1 It's a random integer
import random  or  from random import randint()
secret=random.randint(1,10)
  1. python data type
a ) numerical type : Integer, Boolean, floating point, e Notation ( 1.5e10 )
b ) type conversion:
   int() Convert to integer
   str() Convert to a string
   float() Convert to a floating point number
c ) get information about the type:
   type() function
    a=520
    type(a)
   isinstance() function
    a=12
    isinstance(a,int) ---> return true
    isinstance(a,str) --> return false
  1. common operator for Python value
+ - * / % ** (power operation)  //( The floor division , Results the small )
 Comparison operator  > < >= <=
 Logical operator  and or not
    Priority:
      Power operation **
      Plus or minus  + -
      Arithmetic operator  * / //
         + -
      Comparison operator  < > =
      Logic is bliss  not and or
  1. list — > You can package integers, floats, strings, and so on in 1. Arrays can’t
 create 1 Common list:
   member = [' The little turtle ',' Small pudding ',' The dark night ']
 create 1 Mixed list:
   mix=[1,' The little turtle ' . 3.12 . [1,2,3]]
 Create an empty list:
   empty=[]
 Add elements to the list:
   append(): member.append(' Ferro Eva ')--> Only add 1 A. At the end of the add
   extend(): member.extend(['test','test1'])--> Can only be added as a list . At the end of the add
   insert(): member.insert(1,' The peony ')--> The first 1 Bit insert peony
 Get elements from a list: use an index index .     mix[1]
 Delete elements from the list: use remove() .      mix.remove(' The little turtle ')
            use del .          del mix[3]/mix
            use pop() .         mix.pop()/mix.pop(1)
 List slices: used slice .  mix[1:4]/mix[1:]/mix[:4]
 List operator: >,and,+,*,in/not in
 Friends of the list: dir(list)
          mix.count(' The little turtle ')
          mix.index(' The little turtle ')
 List inversion: use reverse .    mix.reverse()
 List sorting: use sort .      mix.sort()
       mix.sort(func,key)
       mix.sort(reverse=True)
  1. tuple — > Immutable list
 The main differences between list and list:
a ) create and access 1 A tuple:   Most of them use () /,  ; The list with []
b ) tuples cannot modify values
c ) updates and deletes 1 A tuple: temp = temp[:2] + ('test3',) + temp[2:]
  del temp
d ) IN/NOT IN , relational operator, logical operator, multiplication operator, join operator
  1. various built-in methods for strings
#hello Python
 Multi-line comments are used 3 A single quotation mark (or 3 ), such as:
'''hello python
hello world'''
 or
"""hello python
hello world"""
 Also, strings that span multiple lines. You can also use 3 A single quote or 3 Double quotation marks, such as:
'''......'''
 or
"""......"""

0

  1. string formatting replacement
"{0} love {1}.{2:.2f}".format("i","fishc",3.1424)
"{a} love {b}.{c}".format(a="i",b="fishc",c="com")
"{0} love {b}.{c}".format("i",b="fishc",c="com")
 Format symbol meaning:
  %c: Format characters and their ASCII code
  '%c %c %c' % (97,98,99)
  %s: Formatted string
  %d: Formatted integer
  %o: Formatted unsigned 8 Hexadecimal number
  %x: Formatted unsigned 106 Hexadecimal number  %X:...( A capital )
  %f: Format a fixed point number, specifying the precision after the decimal point
  %e: Use science and technology to format the number of fixed points ===%E
  %g: Depending on the size of the value %f or %e===%G
 Format operator auxiliary command:
  m.n  : m Is the minimum total width to display, n It's decimal precision
  -  : for left alignment
  +  : adds a plus sign to a positive number
  #  In: 8 Display in front of the base 0 In the 106 Display in front of the base 0x
  0  : the blank space with 0 fill
 String escape character
  \a: Ring the system bell
  \b , \t , \n
  1. sequence
 What lists, tuples, and strings have in common:
  a ) can be indexed
  b ) index value starts from zero
 Built-in methods:
   list (a) -->help--> Convert to sequence
     list()
       a=list()
     list(iterable)
       b='i love fishc.com'
       b=list(b)
   tuple([iterable])--> the 1 Three iterable objects are converted to tuples
       b=tuple(b)
   str(obj)--> the obj Object to a string
   len(obj)--> return obj The length of the
   max( The sequence / tuples ) / min( The sequence / tuples )
   sum(iterable[,start=0])--> Return sequence iterable . The sum of the
   sorted( The sequence / tuples )--> The sorting
   reversed( The sequence / tuples )--> return 1 Iterator objects
   list(reversed( The sequence / tuples ))--> Return sequence
   enumerate( The sequence / tuples )--> return 1 Iterator objects
   list(enumerate( The sequence / tuples ))--> Returns a list in array form
   zip ( a,b ) --> Merges into lists in tuples
   list(zip(a,b))
  1. function
#hello Python
 Multi-line comments are used 3 A single quotation mark (or 3 ), such as:
'''hello python
hello world'''
 or
"""hello python
hello world"""
 Also, strings that span multiple lines. You can also use 3 A single quote or 3 Double quotation marks, such as:
'''......'''
 or
"""......"""

3

  1. the function has a return value, while the procedure has no return value

  2. scope of function variables (visibility)

#hello Python
 Multi-line comments are used 3 A single quotation mark (or 3 ), such as:
'''hello python
hello world'''
 or
"""hello python
hello world"""
 Also, strings that span multiple lines. You can also use 3 A single quote or 3 Double quotation marks, such as:
'''......'''
 or
"""......"""

4

  1. inline functions and closures
#hello Python
 Multi-line comments are used 3 A single quotation mark (or 3 ), such as:
'''hello python
hello world'''
 or
"""hello python
hello world"""
 Also, strings that span multiple lines. You can also use 3 A single quote or 3 Double quotation marks, such as:
'''......'''
 or
"""......"""

5

19. Recursion:

#hello Python
 Multi-line comments are used 3 A single quotation mark (or 3 ), such as:
'''hello python
hello world'''
 or
"""hello python
hello world"""
 Also, strings that span multiple lines. You can also use 3 A single quote or 3 Double quotation marks, such as:
'''......'''
 or
"""......"""

6

  1. dictionary (key-value)
 mapping / The sequence
 case 1 :
dict1={' Li ning, ':'1 Anything is possible ',' Nike ':'just do it',' adidas ':'impossible is nothing'}

print(' Li ning's slogan is :',dict1[' Li ning, '])

 case 2:
dict3=dict((('f',70),('i',105)))

 case 3:
dict4=dict( The little turtle =' Programming changes the world ',test='test')
dict4[' The little turtle ']=' Modifies the small turtle corresponding value'   --> If not KEY , will be automatically added 1 a KEY

 The built-in method of the dictionary :
a )
dict2['key']--> Access the elements of the dictionary
b )
fromkeys(s[,v]) --> Create or query key
dict1.fromkeys((1,2,3))
{1: None, 2: None, 3: None}
dict1.fromkeys((1,2,3),'number')
{1: 'number', 2: 'number', 3: 'number'}
c )
keys()-->dict.keys() --> Print out the dict All of the key
values()-->dict.values() --> Print out the dict All of the value
items()-->dict.items() --> Print out the dict all (key,value)
get()--> dict.get(key) --> print key The corresponding value
dict.get(key,'text')--> print key The corresponding value If it does not exist, print it text
in The operator  --> key in dict2
clear() -->dict.clear() --> empty dict The data of
copy() -->b=a.copy()  --> Copy a dictionary
id(a)--> To view id
pop(key) --> dict.pop(key) --> The pop-up key
popitem() -->dict.popitem() --> Random popup key
setdefault() -->dict.setdefault(key) --> new key
update()  -->dict.update(dict)  --> Update the dictionary
  1. gather — > Only 1 sex
num={1,2,3,4,5}
set()-->set1=set( The list of / tuples / string )
 Index not supported
 Access the values in the collection :
     use for cycle 11 To find the
     use IN  or  NOT IN
add()-->set1.add(value)
remove()-->set1.remove(value)
 Immutable set :
num3=frozenset( tuples / The list of )
  1. file
#hello Python
 Multi-line comments are used 3 A single quotation mark (or 3 ), such as:
'''hello python
hello world'''
 or
"""hello python
hello world"""
 Also, strings that span multiple lines. You can also use 3 A single quote or 3 Double quotation marks, such as:
'''......'''
 or
"""......"""

9

  1. file system
 Module: packaged file system
os Module:
 Common methods:
os.getcwd(): Return to working directory
os.chdir(path): Change working directory
os.listdir(path=''): List file directory
os.mkdir(path): Create a directory
os.makedirs(path): Create a recursive directory
os.remove(path): Delete the file
os.removedirs(path): Recursive delete
os.rename(old,new): File rename
os.system(command): Operating system shell The command
os.curdir: Refers to the current directory . It's the same thing as theta. '
os.pardir: Refer to the 1 Level directory
os.sep: Outputs the path separator for the operating system
os.linesep: The line terminator used by the current platform
os.name: Indicate the operating system in use
  1. permanent storage
 Storage: pickling
 read :unpickling
 The first step is to import the module pickle
import pickle
>>> my_list=[1,2,3,'test',[23,43]]
>>> pickle_file=open('my_list.pkl','wb') -- "Open the 1 a pickle file
>>> pickle.dump(my_list,pickle_file) -- "The my_list Imported into the pickle_file
>>>pickle_file.close()

>>> pickle_file=open('my_list.pkl','wb')
>>> my_list2=pickle.load(pickle_file) --> the pickle_file Imported into the my_list2
  1. exception handling
 Common standard anomaly :
AssertionErron/AttributeError/EOFError/IndexError/KeyError
/NameError/OSError/OverflowError/SyntaxError/TypeError/ZeroDivisionError

 Catch exception:
try:
     Detection range
except Exception[as reason]:
     The handling code after an exception occurs  print(' code ')
except Exception[as reason] ;
     The handling code after an exception occurs  print('daimai'+ str(reason))
except (Error1,Error2):
     The code that handles exceptions

try:
     Detection range
except Exception[as reason]:
     The code that handles exceptions
finally:
     Code that will be handled anyway

raise Statement throws an exception
raise Exception(' Instruction code ')
  1. rich else statements and concise with statements
else More functionality is generated in conjunction with other statements
with Statement: reduce the workload :
 Don't use with before :
try:
  f=open('data.txt','r')
  for each in f:
    print(each)
except OSError as reason:
  print(' Error! :'+str(reason))
finally:
  f.close()
 use with after :
try:
  with open('data.txt','w') as f:
    for each in f:
      print(each)
except OSError as reason:
  print(' Error! :'+str(reason))
 The import module 3 Kind of way :
a ) import  easygui
easygui.msgbox('test')
b ) from easygui import *
msgbox('test')
c ) import easygui as g
  g.msgbox('test')

 I recommend no more IDLE Running on the EASYGUI
 keywords class
class Turtle:
    # attribute
    color='green'
    weight=10
    # methods :
    def climb(self)
        print('climb tree')

 call :
tt=Turtle() --> Create an object
tt.climb() --> A method is called


oo= object-oriented
oo Features:
1 And encapsulation
2 , inheritance
    class mylist(list):
        pass ---> Means that you inherit only from the parent class and don't make any other changes
    list2=mylist()
3 The polymorphic


self--> The equivalent of c++ the this Pointer to the
>>> class ball:
    def setname(self,name):
        self.name=name
    def kick(self):
        print('i am %s,who kicked me????' % self.name)
a=ball()
a.setname('test')


4 . _init_(self) ---> A constructor

>>> class ball:
    def __init__(self,name):
        self.name=name
    def kick(self):
        print('i am %s,who kicked me????' % self.name)
b=ball('test')


5, Public and private

 Class properties and methods are public by default
name mangling ---> Name adaptation, name renormalization
 Private variables : Add to the variable or function name '__' Double underline
 Access private variable methods :
1, Define methods within the class, indirectly accessing private variables
2,._ The name of the class __ The variable name


6 , inheritance
class derivedclassname(basename):
    ....
 If the same method appears in a subclass as the parent class, override the parent class's method
 Don't want to override the parent method:
1 , calling the unbound parent method
     def __init__(self):
        fish.__init__(self)  ---- First, call the method with the same name of the parent class
            self.hungry=True
2 , the use of super function
     def __init__(self):
            super().__init__()
         self.hungry=True
7 Multiple inheritance
class derivedclass(base1,base2,base3):
    ......

8 The gleanings
Mix-in Programming mechanism

 Class, class object, instance object , Instance properties ( static )
 If the name of the property is the same as the name of the method, the property overrides the method
 The binding :
class bb:
    def printbb():
        print('no zuo no die')
b1=bb()
b1.printbb() ----> Will be in the wrong


9 . 1 Some related BIF :

issubclass(class,classinfo)
1,1 Each class is considered a subclass of its own
2 . classinfo Can be a meta-ancestor of a class object, as long as class And any of them 1 Subclass of the candidate class, returns TRUE

isinstance(object,classinfo)
 Check whether the object belongs to classinfo class
1 If the first 1 A parameter that is not an object is returned forever fasle
2 If the first 2 If a class is not a class, it will be thrown typeerror The abnormal

hasattr(object,name) --> The determination of object If there 'name 'attribute
hasattr(c1,'x')

getattr(object,name[,default]) --> If any property is returned 1 Otherwise return default

setattr(object,name,value) --> to object In the name Attribute assignment vlalue

delattr(object,name) --> delete object In the name attribute

property(fget=none,fset=none,fdel=none,doc=none) Set the properties, set the defined properties
 The method to get the property, the method to set the property, the method to delete the property
class c:
    def __init__(self,size=10):
        self.size=size
    def getsize(self):
        return self.size
    def setsize(self,value):
        self.size=value
    def delsize(self):
        del self.size
    x=property(getsize,setsize,delsize)
c1=c()
c1.x    /  c1.x=19   /c1.size
  1. magic methods (construction and destruction)
 Features:
1 Magic methods are always surrounded by a double underscore, for example __init__
2 The magic method is object-oriented python the 1 cut
3 The magic of magic methods is that they can always be called automatically at the right time

 Construction method:

__init__(self[,...]) --> The return value 1 It is NONE
 Used in instance initialization

__new__(cls[,...])  ---> The first 1 Two initialization methods
 When inheritance 1 This method is called to modify the properties of a class that cannot be modified
class capstr(str):
    def __new__(cls,string):
        string=string.upper()
        return str.__new__(cls,string)

 Destruction method:

__del__(self)   This method is called when the data is not available
 This method is only generated if all instances of the object that were invoked disappear
  1. magic method: arithmetic
__add__(self,other): Define the behavior of addition '+'
 Example:
>>> class new_int(int):
    def __add__(self,other):
        return int.__sub__(self,other)
    def __sub__(self,other):
        return int.__add__(self,other)


>>> a=new_int(3)
>>> b=new_int(8)
>>> a+b  ----> At this time a is self . b is other
-5

__sub__(sub,other): subtraction
__mul__(sub,other): The multiplication
truediv/floordiv/mod/divmod/pow/lshift/rshift/and/xor/or
divmod(a,b) The return value is 1 A tuple: (a//b,a%b)
  1. network socket
socket Provides the relatively low-level network connection and the data transmission function
tcp socket/udp socket/unix socket

 The whole communication process 3 Step:
a ) client to server:
 Import module:
import socket
 create tcp The type of socket:
c=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
 Set to specify ip Address and port tcp The connection
c.connect(('211.121.12.43',80))
 Use on the system netstat The command views the newly created connection :
 Close the connection:
c.close()

b ) server-side monitoring:
import socket
s=socket.socket(socket.AF_INET,socket.sock.SOCK_STREAM)
s.bind(('127.0.0.1',80))
s.listen(1)
while True:
    cs,ca=s.accept() --> create socket Communicate with the client
    cs.sendall('replay')
    cs.close()

c The client sends and receives data :
import socket
c=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
c.connect(('211.121.12.43',80))
 Send 'to the server hello'
c.send('hello')
 Read the server reply data :
c.recv(1024)
c.close()
  1. HTTP library implements HTTP protocol
 The import httplib Module:
import httplib
 create http Instance, specifying the connection hostname and port:
http=httplib.HTTPConnection('itercast.com',80)
 Specify what to get URI:
http.request('GET','/ask') -->get Method to get the specified data, ask Represents the page to visit
 Output the returned web page body Content:
print http.getresponse().read()
 Close the connection:
http.close()

 More simple urllib Library:
 The import urllib The module
import urllib
 create 1 a opener An instance of the
opener=urllib.build_opener()
 Open the specified url
f=opener.open('http://www.baidu.com/ask')
 Read back
f.read()
  1. python connects the modules of mysql
import MySQLdb
conn=MySQLdb.connect(user='root',passwd='',host='127.0.0.1') ---> The connection mysql The default is localhost
 Create a cursor and send it through the cursor sql instruction
cur=conn.cursor()
conn.select_db('database-name') -- . Connect to database , In this example week
cur.execute('insert into userinfo(name,age) value('milo',20)') -- "Executive sql Statements. insert
 Simplified operation mode :
sqli='insert into userinfo(name,age,gender) value(%s,%s,%s)'
cur.execute(sqli,('a',37,'male'))
cur.executemany(sqli,[('test',34,'male'),('test2',36,'female')])
cur.execute('delete from userinfo where id=20') --> Delete the data
cur.execute('select * from userinfo') --> To query the data, but not to display it directly, you can view it using the following method
cur.fetchone()--> in python Displayed on the 1 Rows of data
cur.scroll(0,'absolute')--> Moving target , This is the absolute way
cur.fetchmany(15)--> in python Displayed on the 15 The data . You need to enter data. You have to query
cur.fetchmany(cur.execute('select * from userinfo')) --> through 1 Command to display data
cur.close() --> Close the connection for the cursor
conn.close()  ---> Close the database connection
  1. classes and objects

  2. graphical user interface programming :EasyGui