Python's basic knowledge (according to the reading Python tutorial) 1. String strings can slice, STR [0: 2] is equivalent to STR [: 2], STR [0] cannot change a character in the string. String The front add R can include an escape character. Link list: Str = ['AAA', 'BBB', 'CCC'], can change some of the data in the linked list, which can be different data types, or slice linked lists can be variable sequences. Modify the iterative sequence insecure during iteration (such a case only when using a variable sequence such as a linked list). If you want to modify the sequence of your iteration (for example, copy the selection), you can iterate its replica. This usually uses a slice identification to make this easier. 2.Flow Control if Elif else for in Break and Continue statements, as well as the ELSE clause Break statement and C in the loop, used to jump out of the nearest level for or while loop. The Continue statement is known from C, which means that the loop continues to perform the next iteration. The loop can have an ELSE clause; it is executed when a full list (for for for for) or performing the condition is false (for while), but is not performed in the case where the loop is aborted by BREAK. >>> for n in Range (2, 10): ... for x in == 0: ... IF n% x == 0: ... Print N, 'Equals', x,' * ', N / x ... Break ... else: ... # loop Fell Through Withnout Finding a factory ... Print N,' Is a prime number 'PASS statement does not do. 3.Range () If you need a numeric sequence, the built-in function RANGE () may be useful, it generates an equal line-in-line list. If you need iteratory table index, use Range () and LEN (): >>, 'A', 'Little', 'Lamb', 'A', 'Little', 'LAMB'] >> FOR i below. In Ran (a)): ... Print I, A [i] ... 0 Mary 1 Had 2 a 3 Little 4 LAMB statement Result.Append (b) is a method for LED object Result (Method) . 4. Define Functions 1) DEF FUNCTIONNAME (): return statement returns a value from the function, and returns NONE without an expression. The process will return none after the end. The most useful form that defines a variable number of parameters is to specify the default value for one or more parameters. Important warning: The default value will only be parsed once. Some differences are generated when the default is a variable object, such as a chain table, a dictionary or most class instance. 2) Parameter keyword functions can be called by the form of parameter keywords, such as "Keyword = Value".
Def Parrot (Voltage, State = 'a stiff', action = 'voom', type = 'norwegian blue'): Parrot (1000) Parrot (Action = 'VOOOOM', VOLTAGE = 1000000) Parrot ('a thousand', State = 'Pushing Up The Daisies') Normally, each keyword in the parameter list must come from the formal parameters, each parameter has a corresponding keyword. The default value is not important if the form parameter is not important. Actual parameters cannot assign multiple values at a time - form parameters cannot be used in the same call simultaneously using location and keyword binding values. 3) Variable parameter table Finally, a least commonly used selection is to allow function to call a variable number of parameters. These parameters are packaged into a topology. Before these variable number of parameters, there can be zero to multiple ordinary parameters: DEF FPRINTF (File, Format, * Args): file.write (Format% Args) Parrot ('a million ",' Bereft of Life ' Use the append () method to add an element to the top of the stack. Use the POP () method that does not specify an index can release an element from the stack top 2) Queue You can also use the list as a queue, the queue is such a data structure, the first element is first released (advanced first out) . Using the queue final, call the POP () method to the parameter to release the first entry element to the parameter. 3) Functional Programming Tools For linked lists, there are three built-in functions: filter (), map (), and reduuce (). The Append () method can add an element to "FUNCTION, SEQUENCE" to return a sequence, including all the elements that return value TRUE after all call function (items) in the given sequence. (If possible, the same type will be returned). "MAP (Function, Sequence" is called for each element and returns the return value into a linked list for each element. You can pass multiple sequences, and the function must have a corresponding number of parameters. When executed, use the elements corresponding to each sequence to call the function (if some sequences are shorter than other short, use none instead). If None is incorporated into a function, the direct return parameters are replaced. These two situations we will find "MAP (None, List1, List2) is a convenient way to turn a pair of sequences into elements. "Reduce (FUNC, SEQUENCE" returns a single value, which is constructed: first call the function in the first two elements of the sequence, then call the return value and the third parameter, and execute it. You can pass the third parameter as the initial value. If the sequence is empty, return to the initial value, otherwise the function will first receive the first element of the initial value and the sequence, and then the return value and the next element, so on.
>>> DEF SUM: ... DEF Add (x, y): Return X Y ... Return Reduce (add, seq, 0) ... >>> SUM (Range (1, 11) ) 55 >>> SUM ([]) 0 Do not define SUM (): Because the total value is a general demand, the built-in SUM (Sequence) function is provided in the new version 2.3. 4) Link list derived chain derived provides a simple way to create a list, there is no need to use Map (), Filter (), and lambda. The definition of the returned linked list is usually clearer than the created list. Each chain list includes an expression, zero or more for or if statements after a For statement. The return value is a linked list that consists of an element obtained by the expression after the FOR or IF clause. If you want to get a tuple, you must add parentheses. >>> VEC = [2, 4, 6] >>> [3 * x for x in vec] [6, 12, 18] >>> [3 * x for x in Vec IF X> 3] [12, 18] 5) The DEL statement has a method to delete the element of the specified index from the list: DEL statement. This method can also delete the slice from the linked list (before we assign an empty list to the slice). 6) Tuples and sequences (sequences) We know that there are many universal properties such as indexes and slice operations. They are two kinds of sequence types. Because Python is a language that is inactivated, it can also be added to another sequence type, where there is another standard sequence type: tuple. A tunnel consists of a value separated by several comma, a tuple is like a string, which cannot be changed: a separate element that cannot be given to the tuple (although you can simulate it). A tuple can also be created by including a variable object, such as a linked list. The statement t = 12345, 54321, 'Hello!' Is an example of a group package: value 12345, 54321, and 'Hello!' Are encapsulated into the group. Its reverse operation may be like this: >>> x, y, z = t this call is called a sequence unpacking. The sequence unpacking requires the number of variables on the left to the same number of elements of the sequence. It is important to note that variable parameters are actually a combination of tuple packages and sequence unpacking! Here is a bit asymmetry: Package multi-parameters typically create a tuple, and the unpacking operation can act on any sequence. 7) Dictionary (Dictionaries) The best way to understand the dictionary is to see it as unordered keyword: Value pair (key: value pairs) collection, keywords must be in the same (within the same dictionary). A pair of braces create an empty dictionary: {}. When the initialized chain table, place a comma-separated keyword in the braces: value pair, this is also the way the dictionary is output. The main operation of the dictionary is stored and paid according to keywords. You can also use DEL to delete keywords: value pair. If you store the value with a keyword already existing, the value assigned to the keyword before it will be forgotten. Trying to draw a read value from a non-existent keyword can cause an error.
The keys () method of the dictionary returns a list of all keywords, which is uncertaintable (if you need it ordered, you can only call the sort () method of the keyword list. Use the HAS_KEY () method of the dictionary to check if there is a certain keyword in the dictionary. In the table, the keyword-value pair group is stored, and the dictionary can be directly constructed. Keyword-Value For from a mode, you can use a chain to derive a simple express keyword-value chain list. >>> DICT ([('Sape', 4139), ('guido', 4127), ('Jack', 4098)]) {'Sape': 4139, 'Jack': 4098, 'Guido': 4127} >>> DICT ([(x, x ** 2) for x in vec] # ue l l om {{2 字 技 字 字 字 字 字And the corresponding value can be used with the items () method simultaneously. >>> Knight ':' THE PURE ',' Robin ':' The Brave '} >>> fork, v in knights.Items (): ... Print K, v ... gallahad the Pure Robin The Brave is cycled in the sequence, and the index position and corresponding value can be obtained simultaneously using the Enumerate () function. >>> for i, v in ENUMERATE ([Tic ',' Tac ',' TOE ']): ... Print i, v ... 0 TiC 1 TAC 2 TOE simultaneously cycle two or more sequences It can be interpreted using ZIP (). >>> Questions = ['Name', 'Quest', 'Favorite Color'] >>> Answers = ['Lancelot', 'THE HOLY GRAIL', 'Blue'] >>> for Q, A in Zip (Questions , Answers): ... Print 'What is your% s? IT IS% s.'% (q, a) ... what is your name? it is lancelot. What is your quothesed? it is the holy grail. What is your favorite color? IT is blue. 6. In-depth conditions Control the conditions for the While and IF statements include operators outside the comparison. In and NOT comparison operator review nuclear values are within one interval. The operator IS and IS NOT compare whether the two objects are the same; this is only related to variable objects such as a linked list. All comparison operators have the same priority, lower than all numerical operations. The comparison operation can be passed. For example, a
Logical operators and OR are also referred to as short-circuit operators: their parameters are resolved from left to right, once the result is determined to stop. For example, if A and C are true and B is false, A and b and c will not parse C. When a normal non-logic value is actually, the return value of the short circuit operator is usually the last variable. You can assign a comparison or other logical expression to a variable, for example: 7. The module module is a file including Python definitions and declarations. The file name is the module name plus .py suffix. The module name of the module (as a string) can be obtained by the global variable __name__. If you want to call a function directly, you can usually give it a local name: one variant of the import statement is imported from the semantic table named this module from the imported module. For example: >>> From Fibo Import Fib, FIB2 >>> FIB (500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 This will not be imported into the module name from the local semantic table (for example, FIBO is not defined) ). There is also a variant from the module definition into all naming: >>> from fibo import * >>> FIB (500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 This can be imported into all of the following scriberability ( _) The name of the beginning. 1) When the module search path imports a module called the spam, the interpreter first searches the file named spam.py in the current directory, then searches in the directory list of environment variable pythonpath, and then the path in the environment variable PATH List. If PythonPath is not set, or if the file is not found, then search for the installation directory, in UNIX, usually.: / Usr / local / lib / python. Compile .pyc and .pyo file from .pyc file or .pyo file from the program does not run faster than from .py files; .pyc or .pyo file is only faster when they load. The variable sys.path is a list of strings for the interpreter module search path. It is initialized by environment variables pythonpath. If PythonPath is not within, it is initialized by the built-in default value. You can modify it with standard and string: >>> import sys >>> sys.path.append ('/ ufs / guido / lib / python ") DIR built-in function DIR () is used to search for module definitions by module name It returns a list of storage lists: None parameter calls, the DIR () function returns your current name: You should list all types of names: variables, modules, functions, etc.: DIR () The built-in function and variable name will not be listed. If you want to list this content, they define in standard modules __buildin__: >>> import __builtin__ >>> DIR (__ builtin__) function STR () is used to convert values to the form suitable for human reading, while REPR () Transformation into the form of an interpreter (if there is no equivalent syntax, the SyntaxError exception occurs) There is no explanation in which the object is not adapted, and the STR () will return to the REPR () equivalent value. 7. File Operation Open () Returns a file object, usual usage requires two parameters: "Open (filename, mode)".
>>> f = Open ('/ tmp / workfile', 'W') read the file content, you need to call F.Read (size), the method reads several quantities and returns its content in the form of a string, characters The string length is the size specified by the value size. If you do not specify size or a negative number, you will read and return the entire file. An issue will occur when the file size is twice the current machine memory. Under normal circumstances, the data is read and returned as much as possible. If it is at the end of the file, F.Read () will return an empty string (""). >>> f.read () .readline () reads a single line from the file, the string will automatically add a newline, only when the final line does not take the line, this operation will be ignored. . If the return value will not be confused, if IF f.readline () returns an empty string, then it is said to arrive at the end of the file. If it is an empty line, it will be described as '/ n', one only Contains a string of a wrap. F.ReadLines () Returns a list that contains all the data lines in the file. If a Sizehint parameter is given, the number of bits of more than one line is read, and the row list is returned. This feature is often used to efficiently read large row files to avoid reading the entire file into memory. This operation only returns a complete line. F.Write (string) writes the String content into the file and returns None. f.Tell () Returns an integer that represents the pointer position in the file object in the file, which is measured from the beginning to the number of bits at the pointer. You need to change the file object nuttelling, use "F.seek (offset, from_what)". The pointer moves OFFSET bits from the specified reference position in this operation, and the reference location is specified by the from_what parameter. The from_what value is 0 indicates that the initial starting from the file, 1 indicates that from the current file pointer position, 2 means starting from the end of the file. From_what can be ity, its default value is zero, starting from the file header. After the file is used, call f.close () to turn off the file, release the system resources that open the file. After calling f.close (), call the file object automatically triggers an error. 8. Object-lasting Pickle Python provides a standard module called Pickle. This is an amazing module that can be used to express any Python objects (even some python code blocks (form)!) As a string, this process is called Pickling. Expressing the restructuring object from a string is called unpickling. Objects in the package can be stored in file or objects, or can be transmitted between remote machines over the network. If you have an object X, a file object f, a write-mode, the easiest way to encapsulate only one line of code: pickle.dump (x, f) If F is a file object that is opened in read mode, You can reload this object: x = pickle.load (f) (if you do not want to write the packaged data into the file, there are some other changes available. Complete PICKLE documentation See the library reference manual). Pickle is a standard method that stores the Python object for other programs or itself. Providing this group of techniques is a persistent object ("Persistent Object).
Because the use of Pickle is very wide, many Python expansion authors are very note whether the new data types such as matrices are suitable for packaging and unpacking. 9. Exception Processing TRY Statement works as follows: First, execute the TRY clause (part between TRY and ExcePt keywords). If there is no abnormality, the Except clause is ignored after the TRY sentence is executed. If an exception occurs during the execution of the Try clause, the rest of the subsept will be ignored. If the exception matches the exception type specified after the Except keyword, the corresponding ExcePT clause is performed, and other parts of the TRY clause is ignored. Then continue the code after the TRY statement. If an exception has occurred, there is no branch that matches it in the Except clause, it will pass to the previous TRY statement. If the corresponding processing statement is still not found, it becomes an unprocessed exception, the termination program is run, and the prompt information is displayed. A TRY statement may contain multiple Except clauses, specifying different exceptions, respectively. At most, there will be only one branch is executed. The exception handler will only process an exception that occurred in the corresponding TRY clause, in the same TRY statement, the abnormality that occurs in other clauses is not processed. An Except clause can list multiple exceptions in parentheses, and the last Except clause can omit an abnormal name and use it as a communication. Be careful to use this method, because it is likely to block the real program error, can't find it! It can also be used to print a row error message and then re-throw an exception (which can make the caller better process exception). The TRY ... Except statement can have an else clause that can only appear after all Except clauses. When the TRY is not thrown out, you need to perform some code, you can use this clause. Using the Else clause is better than adding a code in the TRY clause, because this avoids the exception thrown by Try ... Except unexpected interception that does not belong to those code they protected. When an exception occurs, there may be an accessory value as an abnormal parameter. Whether this parameter exists, what type is dependent on an exception type. After the exception name (list), a variable can also be specified for the Except clause. This variable is bound to an exception instance, which is stored in the parameter of Instance.Args. For convenience, the abnormal instance defines __getitem__ and __str__, so you can directly access the print parameters without having to reference .args. When a specific exception has occurred, the programmer can force the abnormality with the RAISE statement. For example: >>> Raise NameError, 'Hithere' Traceback (MOST Recent Call Last): file "
", line 1, in? nameerror: Hithere The first parameter specifies the name of the abnormality thrown, the second specified exception parameter. If you decide to throw an exception without processing it, the Raise statement can make you very Simple re-throwing an exception. You can name your own exception by creating a new exception type. Exception classes typically define any other classes that can be defined from the Exception class. However, in order to maintain a simple, several attribute information is added thereon, in which a newly created module needs to throw several different errors, a usual method is to define an exception for the module. Base class, then give a corresponding abnormal subclass for different error type. The TRY statement has another optional clause that is the functionality that is defined in any case. For example: >>> TRY: ... raise KeyboardInterrupt ... Finally: ... Print 'Goodbye, World!' Regardless of whether there is an abnormality in the TRY clause. If an exception occurs, after the Finally clause is executed It will be reappeared. The TRY clause will also perform a Finally clause via Break or ReturN. The code in the Finally clause is used to release external resources (such as files or network connections), regardless of whether these resources have been successfully utilized. In the TRY sentence, several Except clauses or a finally clause can be used, but both cannot coexist. 10. Private variables Python provide limited support for private members of the class. Any shape such as __spam (to less double underscore At the beginning, the end of the multi-line underscore is then replaced with _classname__spam, remove the ClassName of the front guide, the current class name. This confusing the syntax location of the identifier, so it can be used to define private instances and class variables, methods, And global variables, even saved other classes as private variables. 11. This type of iterator is clear, simple, convenient. The usage of this iterator is common and unified in Python. In the background, for statement The container object calls iter (). This function returns an iterator object that defines the next () method. It is accessed one by one in the container. When there is no subsequent element, NEXT () throws a stopiteration exception notification for statement cycle end Understand the background mechanism of the iterator protocol, you can easily add an iterator behavior to your own class. Define a __itor __ () method makes it returns an object with a next () method. If this class has defined next (), then __iter __ () only needs to return Self: >>> Class Reverse: "iTerator for looping over a sequence backwards" def __init __ (self): self.data = data self. INDEX = LEN (DATA) DEF __ITER __ (Self): Return Self Def next (self): if self.index == 0: raise stopiteration self.index = self.index - 1 return self.data [self.index] >> > for char IN Reverse ('spam'): Print Char 12 Generator Generator is a simple and powerful tool for creating iterators. They write like a regular function, use Yield statements when you need to return data.