Common python knowledge sorting (required) and python sorting
I have been familiar with python for some time. The following describes how to use python basics:
1) avoid two special characters such as '\ N:
A) use the Escape Character '\' B) use the original character 'R' print r'c: \ now'
2) use a single line comment, such:
# Hello Python multi-line comment, using three single quotes (or three double quotes), such: '''hello python hello world' 'or "" hello python hello world "spans strings of multiple rows. You can also use three single quotes or three double quotes, such as ''''... ''' or """......"""
3) embedding double quotation marks and other special characters in a string
A) use the Escape Character '\' B) to enclose the string with single quotation marks. Print ('I l "o" ve fis.com ')
4) condition Branch:
If condition: the condition is true. The operation else: the condition is a false operation. if condition: action elif condition: action else: action python can effectively avoid "hanging else" (if else ing error) condition expression (ternary operator) small = x if x <y else y if x <y, small = x. otherwise small = y asserted assert: when the condition after this keyword is false, the program will automatically crash and throw an exception. assert 3> 4 you can use it to place the checkpoint.
5) while condition:
If the condition is true, the operation for the target in expression is: loop body example: favorite = 'fishc 'for I in favorite: print (I, end = '') range ([start,] stop [, step = 1]) generate a digital sequence break from the value of the start parameter to the value of the stop parameter: Terminate the current loop body. Jump to outer program continue: Terminate this loop and start the next loop (if condition true)
6) The and logical operator can join any expression and obtain a Boolean value.
7) introduce foreign aid:
A) random Module B) randint (), returns a random integer import random or from random import randint () secret = random. randint)
8) python Data Type
A) numeric type: integer, Boolean, floating point, e-log (1.5e10) B) type conversion: int () to integer str () to string float () convert to floating point c) to obtain information about the type: type () function a = 520 type (a) isinstance () function a = 12 isinstance (a, int) ---> true isinstance (a, str) --> false
9) Common operators of Python values
+-*/% ** (Power Operation) // (floor division, result smaller) comparison operator >>=<= logical operator and or not priority: power Operation ** plus and minus signs +-Arithmetic Operators * // +-comparison operators <> = logical operators not and or
10) list --> You can package integers, floating-point numbers, and strings together. Array but not
Create a normal list: member = ['turtle ', 'pudding', 'night'] Create a hybrid list: mix = [1, 'turtle ', 3.12, [1, 2, 3]: Create an empty list: empty = [] add an element to the list: append (): member. append ('fuluapa') --> only one append can be added. Add extend (): member. extend (['test', 'test1']) --> can only be added as a list. insert (): member. insert (1, 'peony ') --> First insert the Peony list to obtain the element: use index. Remove an element from the mix [1] list: Use remove (). Mix. remove ('turtle ') uses del. Del mix [3]/mix uses pop (). Mix. pop ()/mix. pop (1) List slice: Use slice. Mix []/mix [1:]/mix [: 4] list OPERATOR:>, and, +, *, in/not in list: dir (list) mix. count ('turtle ') mix. index ('turtle ') List in reverse order: Use reverse. Mix. reverse () List sorting: Use sort. Mix. sort () mix. sort (func, key) mix. sort (reverse = True)
11) tuples ---> unchangeable list
The main difference with the list: a) Create and access a tuples: most of them use ()/,; the list uses [] B) tuples cannot be modified. c) Update and delete a tuple: temp = temp [: 2] + ('test3',) + temp [2:] del temp d) IN/not in, relational operator, logical operator, multiplication operator, join Operator
12) various built-in methods of strings
Str1 = 'I love fishc.com 'a = str1 [: 6] + 'inserted string' + str1 [6:] capitalize (): str2.capitalize () casefold () ---> all lower case str2.casefold () center (width) --> center, insufficient space to fill count (sub [, start [, end]) --> return the number of times that sub appears in the string. endswith (sub [, start [, end]) --> end with sub? Startswith (prefix [, start [, end]) --> expandtabs ([tabsize = 8]) Starting with prefix --> convert the tab key to space find (sub [, start [, end]) --> whether the sub contains rfind (sub) in the string )... index (sub [, start [, end]) --> similar to sub, but an exception rindex (sub ..)..... istitle ()/isupper ()/ljust (width)/lower ()/strip ()/title ()/lower () join (sub): Use strings as separators, split sub partion (sub): Find the sub string and divide the string into a triple replace (old, new [, count]) split (sep = none, maxsplit =-1) --> swapcase () --> string case flip zfill (width) --> Returns a string with the length of width, not enough space
13) string format 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: formatting characters and their ASCII code '% c % C' % (, 99) % s: formatting string % d: formatting integer % o: formatting unsigned Octal numbers % x: format the unsigned hexadecimal number % X :... (uppercase) % f: format the number of points. You can specify the precision % e after the decimal point: use science to format the number of points ===% E % g: % f or % e = % G formatting operator Auxiliary Command: m. n: m is the minimum total width of the display, n is the decimal point precision-: used for left alignment +: Add a positive number in front of a positive number #: Display 0 in front of the 8-digit, display 0x0: space in front of hexadecimal format fill string escape character with 0 \ a: System bell sound \ B, \ t, \ n
14) sequence
Lists, tuples, and strings share the same thing: a) You can use index B. The index value starts from scratch. The built-in method is: list () --> help --> convert to Sequence list () a = list () list (iterable) B = 'I love fishc.com' B = list (B) tuple ([iterable]) --> convert an iteratable object to a tuples B = tuple (B) str (obj) --> convert an obj object to a string len (obj) --> return the obj length max (sequence/tuples)/min (sequence/tuples) sum (iterable [, start = 0]) --> return the sequence iterable .. Sorted (sequence/tuples) --> sort reversed (sequence/tuples) --> Returns An iterator Object list (reversed (sequence/tuples )) --> returned sequence enumerate (sequence/tuples) --> returned list of an iterator object (enumerate (sequence/tuples) --> returned list of arrays zip (a, B) --> merged into a list in the form of tuples (zip (a, B ))
15) Functions
Definition: def Myfunction (): print ('This is my first function') Call: Myfunction () function parameter: def Myfunction (name, age ): print (name + age + 'test') Myfunction ('gncao ', 'age') function return value: return value parameter (parameter): parameter real parameter (argument): actually passed Parameter Function documentation: Use ''or # In the function body to view function documentation: a) functionname. _ doc _ (four underscores) B) help (functionname) keyword parameter: Avoid parameter chaos def Myfunction (words, name ):...... myfunction (words = 'words123', name = 'name123') default parameter: def Myfunction (name = 'name123', words = 'words123 ')...... collection parameters: add the * def test (* params): print ('parameter length: ', len (params) print ('The second parameter is: ', params [1]) test (1, 'snapshot', 2, 4, 5, 6, 7) def test (* params, exp): print (the length of the 'parameter is: ', len (params), exp) print ('second parameter:', params [1]) test (1, 'turtle ', 23,4, 7, exp = 0)
16) the function has a return value and the process has no return value.
17) function variable scope (visibility)
Local: local --> variables defined in the function, local available global: global --> global accessible when the function attempts to modify global variables, A local variable with the same name as the global variable is created in the function.
18) embedded functions and closures
Global keyword: def myfun (): global count-> global variable count = 10 print (count) nested function: def fun1 (): print ('fun1 () being called... ') def fun2 (): print ('fun2 () is being called') fun2 () can only access the fun2 () closure through fun1 (): In an internal function, reference of external function variables. Into the internal function is the closure def funx (x): def funy (y): return x * y return funy call method: I = funx (8) I (5) or funx (4) (5) enables internal functions to call external function variables through the nonlocal keyword. Def fun1 (): x = 5 def fun2 (): nonlocal x * = x return fun2 ()
19. recursion:
Recursion () def fac (n): if n = 1: return 1 else: return n * fac (n-1) number = int (input ('enter an integer: ') result = fac (number) print (the factorial of' % d is: % d' % (number, result) iteration method: def fab (n ): n1 = 1 n2 = 1 n3 = 1 if n <1: print ('input error ') return-1 while (n-2> 0 ): n3 = n2 + n1 n1 = n2 n2 = n3 n-= 1 return n3 result = fab (20) if result! =-1: print ('total % d was born to Bunny: '% result) recursive method: def fab (n): if n <1: print ('error ') return-1 if n = 1 or n = 2: return 1 else: return fab (n-1) + fab (n-2) result = fab (20) print ('total % d for rabbit birth' % result) but the recursion efficiency is relatively low
20) Dictionary (key-value)
Ing/sequence Example 1: dict1 = {'Lining ': 'Everything is possible', 'nike ': 'Just do it', 'adadad ': 'Impossible is nothing '} print ('Lining's slogan:', dict1 ['liling']) Example 2: dict3 = dict ('F', 70 ), ('I', 105) Example 3: dict4 = dict (Turtle = 'change the world by programming ', test = 'test ') dict4 ['turtle '] = 'modify the value corresponding to the turtle' --> If the KEY is not found, a built-in KEY dictionary method is automatically added:) dict2 ['key'] --> access dictionary Element 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 all key values () of dict --> dict. values () --> Print all values of dict items () --> dict. items () --> Print all (key, value) get () --> dict. get (key) --> Print the value dict corresponding to the key. get (key, 'text') --> Print the value corresponding to the key. If no value exists, print the text in operator --> key in dict2 clear () --> dict. clear () --> clear data copy () --> B =. copy () --> copy dictionary id (a) --> View idpop (key) --> dict. pop (key) --> pop key popitem () --> dict. popitem () --> random pop-up key setdefault () --> dict. setdefault (key) --> Create key update () --> dict. update (dict) --> update dictionary
21) set ---> uniqueness
Num = {1, 2, 3, 4, 5} set () --> set1 = set (list/tuples/strings) does not support index access to values in the set: use the for loop for one-to-one search using IN or not in add () --> set1.add (value) remove () --> set1.remove (value) unchangeable set: num3 = frozenset (tuples/List)
22) File
Input --> process --> output memory ---> disk open () open File: open ('filename/ path', mode = 'rwxabt + U') file object method: f. close () --> close file f. read (size =-1) --> read size characters from the file f. readline () --> open in write mode. If the file exists, add f. write (str) --> write str to the file f. writelines (seq)-> write the seq sequence to the file. Seq should be a string that returns the string sequence f. tell () --> returns the current position. Bookmarks f. seek (offset, from) --> move the file pointer in the file, offset the offset byte from the from for each in f: ----> browse the entire file print (each)
23) File System
Module: packaged File System OS module: common method: OS. getcwd (): returns the operating directory OS. chdir (path): Change the operating directory OS. listdir (path = ''): list file directories OS. mkdir (path): Creates the directory OS. makedirs (path): Create a recursive directory OS. remove (path): delete the file OS. removedirs (path): recursively deletes the OS. rename (old, new): rename the OS. system (command): run the shell command OS of the system. curdir: indicates the current directory. it is equivalent '. 'OS. pardir: indicates the upper-level directory OS. sep: The Path separator OS. linesep of the output operating system: the row Terminator OS. name used by the current platform: indicates the operating system in use.
24) Permanent storage
Storage: pickling read: unpickling first import module pickle import pickle >>> my_list = [1, 2, 3, 'test ', [] >>> pickle_file = open ('My _ list. pkl ', 'wb') -- open a pickle File> pickle. dump (my_list, pickle_file) -- import my_list to pickle_file >>> pickle_file.close () >>> pickle_file = open ('My _ list. pkl ', 'wb') >>> my_list2 = pickle. load (pickle_file) --> Import pickle_file to my_list2
25) Exception Handling
Common standard exceptions: AssertionErron/AttributeError/EOFError/IndexError/KeyError/NameError/OSError/OverflowError/SyntaxError/TypeError/ZeroDivisionError catch exceptions: try: Check range: Failed t Exception [as reason]: print ('code') handle T Exception [as reason] When an Exception occurs; print ('daimai' + str (reason) handle T (Error1, error2): code used to handle exceptions. try: Check range: Failed t Exception [as reason]: code used to handle exceptions finally: the raise statement that will be processed in any case throws an Exception raise Exception ('indicates Code ')
26) rich else statements and concise with statements
Else works with other statements to generate more functions with statements: Reduce workload: Before using with: try: f1_open('data.txt ', 'R') for each in f: print (each) failed t OSError as reason: print ('error: '+ str (reason) finally: f. close () after using with: try: with open('data.txt ', 'w') as f: for each in f: print (each) failed t OSError as reason: print ('error: '+ str (reason ))
Three import methods: a) import easygui. msgbox ('test') B) from easygui import * msgbox ('test') c) import easygui as g. msgbox ('test') is recommended not to run EASYGUI on IDLE
Key words class Turtle: # Attribute color = 'green' weight = 10 # method: def climb (self) print ('climbtree ') Call: tt = Turtle () --> Create an object tt. climb () --> calling method oo = object-oriented oo features: 1, encapsulation 2, inheriting class mylist (list): pass ---> indicates that only the parent class is inherited, list2 = mylist () 3 is not modified. The polymorphism self --> is equivalent to this pointer of c ++ >>> class ball: def setname (self, name): self. name = name def kick (self): print ('I am % s, who kicked me ???? '% Self. name) a = ball (). setname ('test') 4, _ init _ (self) ---> 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. By default, both public and private class attributes and methods are public name mangling ---> name adaptation and name reorganization of private variables: add '_' to the variable name or function name to access the private variable method: 1. Define the method in the class and indirectly access the private variable 2 ,. _ class name__ variable name 6, inheriting class derivedclassname (basename ):.... if the subclass contains the same method as the parent class, the method that overwrites the parent class does not want to overwrite the method of the parent class: 1, call the unbound parent class method def _ init _ (self): fish. _ init _ (self) ---- first calls the method self with the same name as the parent class. hungry = True 2, use the super function def _ init _ (self): super (). _ init _ () self. hungry = True 7, multi-inheritance class derivedclass (base1, base2, base3 ):...... 8. The collection Mix-in programming mechanism Class, Class Object, instance object, and instance property (static). If the property name and method name are the same, the property overwrites the method binding: class bb: def printbb (): print ('no zuo no die') b1 = bb () b1.printbb () ----> error 9 is returned. Some Related BIF: issubclass (class, classinfo) 1. A class is considered as its own subclass 2. classinfo can be the ancestor of a class object, as long as the class and any subclass of a candidate class, returns TRUE isinstance (object, classinfo) to check whether the object belongs to classinfo Class 1. If the first parameter is not an object, fasle 2 is always returned. If the second parameter is not a class, hasattr (object, name) --> determines whether the object has the 'name' attribute hasattr (c1, 'x') getattr (object, name [, default]) --> if 1 is returned for an attribute, otherwise, default setattr (object, name, value) is returned. --> assign vlalue delattr (object, name) to the name attribute of the object) --> delete the name property (fget = none, fset = none, fdel = none, doc = none) in the object and set the property acquisition method, set the property method. The method for deleting 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
29) magic methods (constructor and constructor)
Features: 1. The magic method is always surrounded by double underscores, for example, _ init _ 2. The magic method is all about object-oriented python 3, the magic of magic methods is reflected in the fact that they can be automatically called to construct methods when appropriate: _ init _ (self [,...]) --> the return value must be NONE in instance initialization _ new _ (cls [,...]). ---> when the first initialization method inherits a class that cannot be modified, call this method to modify the attribute class capstr (str): def _ new _ (cls, string ): string = string. upper () return str. _ new _ (cls, string) destructor: _ del _ (self) when the data is not applicable, this method is generated only when all instances that call this object disappear.
30) magic method: arithmetic operation
_ Add _ (self, other): defines 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 ----> in this case, a is self and B is other-5 _ sub _ (sub, other): subtraction _ mul _ (sub, other ): the return value of multiplication truediv/floordiv/mod/divmod/pow/lshift/rshift/and/xor/ordivmod (a, B) is a ancestor :( a/B, a % B)
31) network socket
Socket provides the underlying network connection and data transmission functions. tcp socket, udp socket, and unix socket take three steps in the entire communication process: a) Client Connection server: import module: import socket to create a tcp socket: c = socket. socket (socket. AF_INET, socket. establish a tcp connection to the specified IP address and port c. connect ('2017. 121.12.43 ', 80) run the netstat command on the system to view the new connection: Close the connection: c. close () B) server listening: import socket s = socket. socket (socket. AF_INET, socket. sock. SOCK_STREAM) s. bind ('2017. 0.0.1 ', 80) s. listen (1) while True: cs, ca = s. accept () --> Create socket and Client Communication cs. sendall ('replace ay') cs. close () c) send and receive data from the client: import socket c = socket. socket (socket. AF_INET, socket. SOCK_STREAM) c. connect ('2017. 121.12.43 ', 80) sends 'hello' c to the server. send ('hello') reads server reply data: c. (recv (1024) c. close ()
32) Implement the HTTP protocol in the HTTP Library
Import httplib module: import httplib to create an http instance and specify the host name and port: http = httplib. HTTPConnection ('itercast. com ', 80) specifies the URI to be obtained: http. request ('get', '/ask') --> GET method to get the specified data. ask indicates that the webpage body returned by the page to be accessed is print http. getresponse (). read () Close connection: http. close () Simpler urllib Library: import urllib module import urllib to create an opener instance opener = urllib. build_opener () Open the specified url f = opener. open ('HTTP: // www.baidu.com/ask') read the returned content f. read ()
33) connect python to the mysql Module
Import MySQLdb conn = MySQLdb. connect (user = 'root', passwd = '', host = '2017. 0.0.1 ') ---> connect to mysql. By default, the cursor is created by localhost and the SQL command cur = conn is sent through the cursor. cursor () conn. select_db ('database-name') -- "connect to the database. In this example, week cur.exe cute ('insert into userinfo (name, age) value ('milo', 20) ') is used )') -- execute the SQL statement. Simple insert operation: sqli = 'insert into userinfo (name, age, gender) value(s,s,s,%s%'cur.exe cute (sqli, ('A', 37, 'male') cur.exe cute.pdf (sqli, [('test', 34, 'male'), ('test2', 36, 'female ')]) cur.exe cute ('delete from userinfo where id = 20 ') --> Delete the data cur.exe cute ('select * from userinfo') --> query the data, but it cannot be directly displayed. You can use the following method to view the cur. fetchone () --> display a row of data on python cur. scroll (0, 'absolute ') --> move the indicator. This is an absolute mode of cur. fetchmany (15) --> display 15 entries in python Data. You need to enter the data. You must first query cur.fetchmany(cur.exe cute ('select * from userinfo') --> use a command to display the data cur. close () --> close the connection conn of the cursor. close () ---> close database connection
The above python common knowledge sorting (this article is required) is all the content shared by the editor. I hope to give you a reference, and I hope you can provide more support to the customer's house.
28) classes and objects
27) graphic user interface programming: EasyGui