Statement and Grammar of the python2.3-principle

Source: Internet
Author: User

Label:

This section is from the fourth edition of the Python Learning Manual, Part III

I. Introduction to the Python Statement (chapter 10th)

1, first remember a concept: A, the program is composed of modules; B, the module contains the statement; C, the statement contains the expression; d, the expression establishes and processes the object. The syntax of Python consists of statements and expressions that process objects and nest them in statements, which are more logically related to the implementation of program operations, where statements are generated by objects, and some statements completely generate new object types (functions, classes). Statements are always present in modules, and the modules themselves are managed by statements.

2. The following is a Python statement table:

A, assignment statements are presented in different grammatical forms, for example: Basic, sequential, extended, and so on; B, print is not a reserved word in 3.0, nor is it a statement, but a built-in function call, because it is always a single line, usually as a statement type; C, Yield is actually an expression, not a statement, which is usually used on a single line, so it is included in the table above, but the script occasionally assigns a value to its result, unlike print, which, as an expression, is also a reserved word.

3, most of the above table also applies to 2.6, but if you use 2.6 or earlier version note: A, nonlocal is not available; B, print is a statement, not a built-in function; C, 3.0 exec code execute built-in function is a statement with a specific syntax Because it supports the form of parentheses, usually using its 3.0 invocation form in 2.6, the try/except and try/finally statements in D, 2.5 are merged; E, Whit/as is an optional extension, and usually it is not available unless you run __future__import with_statement to open it.

4. In the C-series, the discriminant expression needs to be enclosed in parentheses (x>y), and the statement needs to be enclosed in curly braces {}, whereas in Python you use a colon: instead of a curly brace, the general first line ends with a colon, and the next line of nested code is written in indented format:

In Python: A, parentheses are optional, such as if (X>y) is written if x>y;b, the grammatical component that does not appear in Python is a semicolon, the end of the line ends (this view is good, is bad no comment, I like the semicolon); C, the end of the indentation is the end of the code block , do not need to enter curly braces, as in C, or input begin/end,then/endif like Matlab, in Python, it is by indentation to determine the beginning and end of the code block, Python does not care about the way and distance of indentation, Only know that all statements in a single nested block must be indented at the same distance, or they will get an error.

5, in the above 4 python still has a few special cases: A, although many times is one line, but also have a line of multiple, this time the middle with a semicolon separated, as a statement delimiter: a = 1;b = 2;print (a+b), but these three can not be compound statement, must be a simple statement, such as assignment operations, printing and function calls, and so on; B, above is a line of multiple, here is a multiline one, in parentheses (), square brackets "" and the Dictionary of curly braces {}, which can span several lines of code in the program:

There is another way to do this without the three brackets:

(This method is not recommended). And for when the line of the statement can be followed such as if X>y:print (x).

6, in the need to write a standard "read, calculate, print" loop program: in Python interactive loop of the typical template code may be as follows:

While is the most common loop statement, input is used for general console output, prints an optional parameter string as a hint, and returns a reply string entered by the user, using a special single-line if statement in a nested block of code; break jumps out of the loop.

7, use the test input data to handle the error, an example if statement to avoid errors caused by the exception:

8. Use a try statement to handle the above error:

After the try is followed by the Code main code block (we try to run the code), followed by the except section, to the exception handler code, and then the else part, if there is no exception in the try section, execute this part of the code. Python executes the try section first, and then runs the except section (if there is an exception) or else part (if no exception occurs), where else is combined with try, not and if.

9, nested code three layer:

This code while contains a if-elif-else where else contains a if-else. A print () is added after the while external.

Second, assignment, expression and printing (11th chapter)

Assignment value: (said before, actually this book really and know on the same, good wordy, 1162 pages many are in the long-winded): A, the assignment statement establishes the object reference value, B, the variable name will be created when the first assignment, C, the variable name must be assigned before the reference, D, perform implicit assignment of some operations. The form of an assignment statement is as follows:

Line fifth above, is to match the first letter of the right string to a, with the remainder to match B: that is, A is assigned to ' s ', B is assigned to ' Pam '.

1. Tuple assignment statements can be variable-swapped when no zero-hour variables are established, such as: Nudge = 1;wink = 2; >>>a,b = Nudge,wink; or >>>[c,d] = [Nudge,wink] ; interchange can be so >>>nudge,wink = Wink,nudge. The original tuple and list assignment statements in Python are finally generalized and the right side can be any type of sequence, as long as the lengths are equal, for example:

However, the sequence assignment statement actually supports any iterated object on the right, not just any sequence, which is a more general concept. However, to be more generic, you can use shards such as:

Or the low end uses a for loop to make the loop assignment:

A sequence unpacking assignment statement can also produce another common use for Python:

2. In the 3.0 extension sequence unpacking, the sequence assignment becomes more general, making the process easier, a name with a single asterisk, which can be used in an assignment target to specify a more generic match for the sequence-a list is paid with an asterisk name, which collects all items in the sequence that are not assigned to another name ;

This extended sequence-unpacking syntax is valid for any sequence type, not just for lists, such as >>>a,*b= ' spam ', or >>>a,*b,c = ' spam '; in extended sequence unpacking, some of the boundary conditions deserve attention. , a name with an asterisk may match only a single item if it is not allocated enough, but it is always assigned a list: second, if there is nothing left for the asterisk, then an empty list is assigned to him, regardless of where it appears:

However, if there is more than one name with an asterisk, or if the value is less, without the name with an asterisk (as before), and if the name with the asterisk itself does not have an edge written to a list, an error will be raised:

>>>a,*b,c,*d = seq;>>>a,b = Seq;>>>*a = seq; all three are wrong; >>>*a, = seq This adds a comma, indicating that it is a list The result is a = [1,2,3,4];

3, here a useful convenient form, but said must be used in Python 2.X, so here slightly

4, in 3.0, the extension assignment may appear after the word for, and the more common use is a simple variable name:

The result is A,*b,c = (1,2,3,4), *b = [2,3], or the following form is used in 2.6 to simulate:

5, Multi-objective assignment: a=b=c= ' spam ', here three variables but share an object, but if the >>>a=b=0; >>>b = b+1; so that A and B are two objects, because numbers or strings cannot be changed, so after Assignment B gets a new object instead of the original object, but when you set the variable initial value to an empty mutable object (list or dictionary), you should be careful:

So if it's a mutable object, it's best to initialize it separately.

6, enhance the assignment statement, from the C language borrowed from:

If you need to add a single element to the end of the list, you can merge or call Append, but to add a set of elements to the end, you can use the merge again, or call the Extend method of the list:

In both cases, the side effects of merging on shared object references may be smaller, but will run slower than the equivalent in-place form, which is to create a new object, copy the left side to the list, and then copy the right side to the list, while the same method call adds the item directly to the end of a memory. However, when using the enhanced assignment statement to extend the list, Python automatically calls the faster extend method instead of the slower "+" merge operation, so "+ =" implies that the list is processed in place. In the case of all shared references, only the objects referenced by other variable names are modified, and their differences may be reflected:

This is only important for mutable objects such as lists and dictionaries, and is quite rare (at least until the program code is affected), so if you do not want to be the default shared reference value, copy the Mutable object.

7. Variable naming rules: A, grammar: (underscore or letter) + (any number of letters, numbers or underscores), B, case-sensitive, C, prohibit the use of reserved words:

The table above is for 3.0, 2.6 slightly different: print is reserved word, exec is reserved word, nonlocal is not reserved word, earlier on slightly P305 page. Most of the python reserved words are lowercase, but the variable names in the built-in scopes that follow are different. Because the module variable name in the import statement becomes a variable in the script, this restriction extends to the file name of the module, such as and.py and my-code.py, but cannot be imported, because its variable name does not have a ". py" extension, it becomes a variable in the code. Will conflict with the reserved word. PS: In the Jpython version of the Python implementation, user-defined variable names can occasionally be the same as Python's reserved words.

Naming conventions: These are not required, but in practice it is usually observed that a, variable name starting with a single underscore (_x) will not be imported by the From module Import * Statement (Chapter 22); B, preceded by an underscore variable name (__x__) is a system-defined variable name, There is a special meaning to the interpreter, C, the variable name (__x), which begins with two underscores, but no two underscore at the end, is the local variable of the class (30); d, when run through interactive mode, only a single underlined variable name (_) Saves the result of the last expression. There are some such as class variable names usually start with a capital letter, and the module variable name starts with a lowercase letter, in addition, the variable name self, although not reserved words, but in the class has a special role, in the 17th chapter will be explained in the following, involves the built-in variable name, these are predefined variable names, but not reserved words. More information can be found by searching for "Python PEP 8".

8, usually in the following two cases the expression is used as a statement: A, calling functions and methods, B, printing values at the interactive mode prompt, the following table is the form of some common expression statements, functions and methods are called in parentheses after the function, method variable name, An object with 0 or more arguments (this is the expression that evaluates the object):

The last two of the above table are special, in 3.0, printing is a function call and usually writes a line on its own, and the yield operation in the generator function is usually written as a statement, both of which are just real examples of expression statements.

9, for beginners often make mistakes is >>>l = L.append (X) so, but the result is l= None, because the list calls append, sort or reverse such a modification of the same place, must be the list to be modified , but these methods, after modification, do not return the list, but return none.

10, Python printing and the concept of file and stream are closely connected: A, File object method, the Nineth chapter describes a number of file object methods written to the file (such as; File.write (str)), the file write method is to write a string to any file, Print defaults to printing objects to the stdout stream, adding some automatic formatting, and different file methods, when using a print operation, you do not need to convert the object to a string; B, the standard output stream, In Python it can be used as a stdout file object in the built-in SYS module (such as Sys.stdout), making it possible to use the Write method of a file to simulate print, but print is easy to use, so it is easy for text to be printed to other streams or files.

11, in 3.0 the form of the print function is:

, the square brackets are optional, and the values that follow are given the default values of the parameters, and this built-in function prints the text representation of one or more objects separated by the string Sep, followed by the string end, and printed to the stream file. Sep, end, and file if given, must be given as a keyword argument, using the "name=value" syntax to pass arguments by name instead of location (18 in depth): A, Sep is inserting a string between the text of each object, the default is a single space, Passing an empty string will suppress the delimiter; B, end is a string added at the end of the printed text, the default is \ n line break, passing an empty string will avoid moving to the next input line at the end of the printed text----the next print will remain added to the end of the current output line; C, file specifies the files to which the text will be sent, standard leaves, or other similar files; By default, Sys.stdout, any object with a write (string) method like a file can be passed, but the real file should already be opened for output.

12, in the 3.0 print may be more simple, here is an example:

On the right is the processing of the delimiter by assigning Sep to the value.

is to assign a value to the end assignment and to the SEP mix, at least one point, after the argument.

If you want a more specific format, do not do this, or follow the previous string formatting, and then print it once

13, the print statement is only the human nature of Python, provides a simple interface to the Sys.stdout object, plus some default formatting, complex points can be as follows:

This program calls the Write method of Sys.stdout, which typically has the following relationship between print and sys.stdout: print (x, y) is equivalent to >>>import sys;>>> Sys.stdout.write (str (X) + ' +str (Y) + ' \ n '); the latter is more complex, but the latter is more flexible, for example:

, here we reset the sys.stdout to an open file object (additional mode). Once reset, any print statement in the program writes the result to the end of the file Log.txt, not the original output stream. You can even reset the sys.stdout to a non-file object as long as the object has the expected protocol (write method). When the object is a class, the printed text can be positioned and processed in any way.

14, how to save the original output stream so that after printing the file can be switched back, in 2.6 and 3.0, you can use the __stdout__ property in the Sys module, which is the original value of Sys.stdout when the program starts. However, after the modification, it is necessary to restore the sys.stdout to sys.__stdout__ to return the value of the original stream:

It can be seen that such a print extension is sometimes superfluous, The file keyword in 3.0 allows a single print call to send its text to a file's write method without actually resetting the sys.stdout, which is temporary, and the normal print is then printed to the original output stream. (2.6 is with print >> log,x,y,z; the log here is "Log.txt").

15, the above is related to the version of the print, the following version of the Independent printing: If you write a 2.6 print statement, then use 3.0 of the 2to3 conversion script is called in 3.0. Or you can write 3.0 of the print function in 2.6 of the Code, and support the variant of the function call with the following statement:

This statement modifies 2.6 to support the 3.0 print function, and if it needs to be really portable, format the print string as a single object, using a string format expression or method invocation:

16. Print and sys.stdout are equivalent, the PRINT statement simply transmits text to the Sys.stdout.write method, such as the ability to transfer printed text to the GUI window, or to define an object with the Write method, he will do the required send work, the following introduction of the class will have this skill:

The code above can work because print is a polymorphic operation: Sys.stdout It is important that there is a method (interface) called write:

The Raw_input () function that is built into print is read from the Sys.stdout file. PS: Because the printed text enters the stdout stream, which is also the way to print HTML in CGI scripts, which can also be implemented in the OS in Shell syntax:

Iii. if test and grammar rules (12th)

The IF function in Python is similar:

,

,

1. In Python, there is no switch or case statement, in Python, the multi-branch is written as a series of if/elif tests, or the dictionary is indexed or searched list:

Because you have a default option in the If series, you can use get in the dictionary as well:

2, Python syntax rules: Python has simple and statement-based syntax, but some features still need to know: A, the statement is run by one, unless it is not written, if this will affect the process is called the control flow statement; B, block and statement boundary will be automatically detected; c, compound statement = First row + ":" + indent statements, compound statements follow the same format: the first line terminates with a colon, the second line is followed by one or more nested statements, usually indented under the first line, the indented statements are called blocks (groups), and d, blank lines, spaces, and comments are usually ignored; E, document Strings (docstring) are ignored , but remains and is displayed by the tool: Unlike the # comment, the document string is persisted at run time for viewing, and the document string appears only in the string at the top of the program file and some statements, although Python ignores the content, but it is automatically attached to the object at run time and can be displayed by the document tool.

3, in general, Python statements can not cross the line, but: A, use such as (), "", {} such parentheses will be able to cross the line, B, backslash end; C, the string of the triple quotation string block, adjacent string constants can be implicitly connected; D, other rules, such as semicolons can put more than one line.

4, such as this bracket:

, parentheses can hold expressions, function arguments, first rows of functions, tuples and generator expressions, and anything that can be put into curly braces (dictionaries and set constants in 3.0, collections, and dictionary parsing).

5, the Boolean operators of Python and C are somewhat different, in Python: A, any non-0 numeric or non-null objects are true, B, number 0, empty objects and none of the special objects are considered false; C, comparisons and equivalence tests are recursively applied to data structures; The comparison and equality tests return TRUE or the False;e, Boolean, and OR operators return TRUE or false operands. : x and y; x or y; not X.

6, in Python Boolean and and or return is a true or False object, not true or false:or test from left to right to evaluate the object, return the first true operand, if or both are false, then return the second, and test from left to right to calculate the object, Returns the first false object:

7, If/else Three-dimensional expression, such as in the CPP? : three-dimensional expressions:

When x is true, y is executed when x is false and z is executed. It is also similar to using the following expressions in Python, because the bool function converts x to the corresponding integer 1 or 0. It can then be used to pick the true and false values from a list:

For example

8.

These two are the benefits of or, can be used to choose a fixed size set of non-empty objects, but because of or truncation operation, left and right side is the function, advance execution, and then compare the results, do not directly compare functions; expressions ((A and B) or C) are always used to emulate if/else statements. PS in the later operator overloading section, when we use the class to define a new object type, you can use the _bool_ or _len_ method to specify its Boolean attribute (2.6 is called _nonzero_).

Iv. while and for Loops (chapter 13th)

The while statement is the most common iteration structure in a Python statement, in short, as long as the top test always evaluates to true, the following block of statements is executed, in the form:

1, break, slightly, continue, slightly, pass, do not do anything, just occupy the position; else, it will only be executed if the loop is left normally (that is, you have not encountered a break before):

For pass, in 3.0, it is allowed to use any place where an expression can be used ... (three consecutive points) to omit the code, since the ellipsis does nothing and can be used as an alternative to the pass statement.

2, because the assignment statement in Python is only a statement, not an expression, which excludes a C easy to make mistakes, "= =" hit "=", so in the test section of the loop does not need to write the assignment statement, there are three alternative methods:

For is a general-purpose sequence iterator that iterates through the elements within any ordered sequence object, and can be used for strings, lists, tuples, other built-in objects that can be iterated, and new objects created later by the class. Its general format is:

It's full format:

3. When running for, the elements in the sequence object are assigned to the target one by one, then the loop body is executed for each element, and the loop body typically uses the target of the assignment to refer to the current element in the sequence as if it were a cursor traversing the sequence. The variable name used as an assignment target in the first row is usually a variable in the scope of the for, which is not special or even modified in the body of the loop, but when control returns to the top of the loop, it is automatically set to the next element in the sequence, and after the loop, the variable generally refers to the most recently used element. That is, the last element in the sequence, unless you exit the loop with a break statement.

4. Any assignment target can be syntactically used after the FOR keyword:

Other examples are not written, but not written.

5, when the file read, there are several methods:

The last one is the recommended method, which is not only simple, but also valid for any size file, and does not load the entire file into memory at once, and the iterator version may be faster, but the I/O performance is slightly worse in 3.0.

6, generally for more than while easy to write, and execution is faster, but sometimes need a specific way to iterate, such as every other element or two elements, or in the same for loop, in parallel to traverse more than one sequence. Although it can be done with a while loop and manual index operations, Python provides two built-in functions for iterating within a for loop: A, the built-in range function returns a series of consecutive incremented integers as an index in for, and B, the built-in zip function returns a list of tuples of parallel elements, Can be used to traverse the entire sequence within a for.

7, the 6:range function is a common tool, although commonly used in the For loop to produce an index, but also can be used in any need for an integer list of places, in 3.0, this is an iterator, you can produce the element as needed, so you need to include it in a list call to the one-time display results:

Range when there is only one parameter, there will be "0,x", two parameters when "x, Y", three parameters "x, y", and z is the step size. Generally speaking, for is better than while and use range as little as possible because it has no in expression fast. For example, the following code:

, this can be achieved by jumping, this method is easy to write, and easier to read, the only advantage of using range is that it does not copy the string, and does not create a list in 3.0, which saves memory for large strings.

, this code on the left again reminds us that the x here is just a reference, and even if used, it still cannot change the value in L, the next time for the loop, the X will automatically become and L in the second value, equivalent to traverse the position, not the element, the right side through the index implementation to modify the value in the list. If you use the while, it may be slow to run, but you can use "x+1 for X in L" to regenerate a list.

8. Built-in function Zip also lets us use multiple sequences in for-parallel. In the basic operation, the zip takes one or more sequences as parameters, then returns a list of tuples, matching the side-by element of those sequences into pairs, because the zip is also an iterative object in 3.0, so it must be included in a list call to display all the results at once:

This is 2 parameters, three parameters are the same, when the length of the parameter is different, the zip will be the shortest sequence length to truncate the resulting tuple. (2.6 of the map here does not introduce, slightly)

9. A zip call can also be used to generate a dictionary:

, but in the 2.2 extremely later versions, you can skip the for loop completely and pass the ZIP key/value list directly to the built-in Dict constructor:

10, in the For loop, there will be a counter that records the current offset value, a new built-in function, called Enumerate:

The Enumerat function returns a generator object: Simply put, this object has a __next__ method, has the next built-in function to call it, and it returns a (index,value) tuple for each iteration of the loop. Tuples can be unpacked by tuple assignment operations in a For loop:

It automatically executes the iteration protocol:

V. iterators and parsing, Part I (chapter 14th)

The concept of "iterative objects" is quite novel in Python, but it is common in language design, basically, that is the generalization of sequence concepts: If an object is an actual saved sequence, or an object that can produce one result at a time in an iterative tool environment (such as for), it is considered to be iterative. In summary, an iterative object includes an actual sequence and a virtual sequence that is computed as required.

1. File iterator: Each time the ReadLine method is called, it advances to the next column. When the end of the file is reached, an empty string is returned. However, the file also has a method, called _next_, almost the same effect: each time the invocation, the next line in the file is returned, the only difference is that when the end of the file is reached, _next_ throws the built-in Stopiteration exception instead of returning an empty string:

The term "iterative" in this section refers to an object that supports ITER, while an "iterator" refers to the object returned by ITER that supports next (I). This interface is an iterative protocol in Python: an object with a _next_ method advances to the next result, and at the end of a series of results, it throws a stopiteration. In Python, any such object is considered to be iterative, and any such object can be traversed with a for loop or other iteration tool because all iteration tools work internally to invoke _next_ in each iteration and catch stopiteration exceptions to determine when to leave:

This code is the best way to read a text file because it is simple, runs fastest, and is best in terms of memory usage. Although >>>for line in open (' scripy1.py '). ReadLines (): This still works, but it's not the best way, and the effect is pretty bad in memory, because in fact, the version is a one-time load of the entire file into memory, Although using the While method:

But because the for is implemented in the C language, while the while is running Python bytecode through a Python virtual machine, it is relatively slow, but in 3.0 there is a timing technique that can be used to measure the speed of the method.

2, in order to support manual iterative code, 3.0 provides a built-in function next, you can automatically invoke an object's _next_ method, Next (X) is equivalent to X._next_ (), but the former is much simpler. Technically, the iterative protocol is worth noting that, at the start of the For loop, it passes through to the ITER built-in function to get an iterator from an iterative object that contains the required next method. However, this is not necessary for a file, because the file object itself is its own iterator, and the file has its own _next_ method, so there is no need to return a different object:

File

But the list and many other built-in objects, not their own iterators, because they support opening iterators multiple times, such objects need to call ITER to start the iteration:

3, in addition to files and lists, other types also have their appropriate iterators, such as the classic way to traverse the dictionary key is to get a list of keys, but in the newer Python, the dictionary has an iterator, in the iterative environment, will automatically return a key: >>>i = iter (D); >>>next (i); >>>next (i); Other Python objects Rachel also supports iterative protocols, so you can use them in for, such as the results of shelves and Os.open are iterative:

The Popen object supports the P.next () method in 2.6, supports the P._next_ () method in 3.0, and does not support the next (P) built-in function. So now you know how the enumerate tool works:

4, list parsing looks like a reverse for loop, for example:

, the list resolution is written in a square bracket, the method is easy to write, and runs fast, to run the expression, Python executes an iteration through L within the interpreter, assigns x to each element in order, and collects the result of the left expression on each element. Recommended for use.

5, because the ReadLines method in the file object contains a newline symbol (\ n) at the end of the line, how to remove it,

The second expression does a lot of implicit work, Python scans the file and automatically builds a list of the results of the operation, because most of the work is done in the Python interpreter, which may be much faster than the equivalent statement, and for a particularly large file, the speed of list parsing has obvious advantages, and the for preceding expression can be such as: Line.rstrip (). Upper () and so on.

6. The For loop nested within the expression can have a related if clause to filter the result items that are not true for the test:

The IF clause checks each line read from the file to see if his first character is P, and if not, omits the row from the result list. More complex for loops are:

7. Each tool that is scanned from left to right in the object uses iterative protocols, such as for loops, list parsing, in member testing, map built-in functions, and built-in functions like sorted and zip calls, all using an iterative protocol that, when applied to a file, All of these iterators that use file objects are automatically scanned by row:

>>>uppers = [Line.upper () for line in open (' script1.py ')];>>>map (Str.upper,open (' script1.py ')); >>>list (Map (Str.upper,open (' script1.py ')));>>> ' y = 2\n ' in open (' script1.py ');>>> ' x = 2\n ' In open (' script1.py '). The map function is a built-in function that applies a function call to each item of an incoming iterator object. Map is similar to list parsing, but it is more restrictive because he needs a function instead of an arbitrary expression. In 3.0, it also returns an iterative object itself, so we need to include it in a list call to force it to give it all at once, as map-like list parsing is related to loops and functions, followed by subsequent introductions. In some built-in functions, unlike map and other functions, sotred returns a real list in 3.0 instead of an object that can be iterated.

8, then 7, other built-in functions also support an iterative protocol, such as sum to calculate the total number of any iterated object, if any or all of the items in an iterative object are true, the any and all built-in functions return True;max and Min, respectively, to return one of the largest and smallest items in an iterative object. Strictly speaking, the Max and Min functions can also be applied to files-they automatically use the iteration protocol to scan files and select rows with the highest and lowest string values, respectively. In the list and tuple built-in functions, the string join method even includes sequence copying, all of which will work on an open file and automatically read one line at a time:

9, compared to the above Dict call accepts an iterative zip result, set of call Memory 3.0 in the new set parsing and dictionary parsing expressions:

However, both set parsing and dictionary parsing support extended syntax for list parsing, including if testing:

10, the last introduction of the iterative environment, also in the 18 chapter learning, in the function call a special form of *arg, he will be a set of the value of the package as a single parameter. And of course he will accept any iteration object, including the file:

Because the parameter unpacking syntax in this call accepts an iterative object, it is also possible to use the zip built-in function to zip over the tuple unzip, as long as the previous or nested zip result parameters are used for any other zip call:

11, 3.0 and 2. X is more emphasis on iterations, except for iterations related to built-in types such as files and dictionaries, the dictionary method keys, values, and items return and iterate objects in 3.0, just as the built-in function range, map, zip, and filter do, they return objects that can be iterated, Results are generated in 3.0 based on the request, instead of the build results list in 2.6. Although this can save memory, but to some extent it will affect our coding, which means that in interactive mode to display the results require additional input, which is useful for larger programs, when calculating a large list of results, such a delay calculation can save memory and avoid pausing.

12, Range iterator, returns an iterator that produces the number in the range as needed instead of building a list of results in memory, and if a range list is required, you must use the list (range ... ) to force a true range list: >>>r = Range (10), the result is R is range (0,10), >>>i = iter (R), >>>next (I), and the result is 0, Next, the result is 1, and if you use >>>list (range (10)), the result is "0,1,2,3,4,5,6,7,8,9"; in 3.0 the Range object supports only iterations, indexes, and Len functions. They do not support any other sequence operations: >>>len (R), and result is 10;>>>r[0] The result is 0.

13. Similar to range, the map, zip, and filter built-in functions also become iterators in 3.0 to conserve memory, instead of generating a single result list in memory, all of these three functions are not only treated as an iterative object in 2.X, but also return an iterative result in 3.0. Unlike range, they are their own iterators, in other words, they cannot have multiple iterators that hold different positions in those results on their results:

14. Zip built-in function that returns an iterator that works the same way:

There's also the filter built-in function behind the learning, as well:

Filter can accept an iterative object and process it, returning an iterative object and producing the result in 3.0.

15. The Range object supports Len and index, and when it is not its own iterator, and it supports multiple iterators on its results, these iterators will remember their respective positions;

, x instead, zip, map, and filter do not support multiple iterators on the same result: that is, the three different I1 will be equal to I2, and the result is an iterator.

16. In the 3.0 dictionary, the keys, values, and items methods return an iterative view object that produces one result item at a time instead of producing the full list of results once in memory. View items remain in the same physical order as those in the dictionary, and reflect changes made to the underlying dictionary:

Like all iterators, we can always force a real list by passing a 3.0 dictionary view to the list built-in function, but this is not always necessary, except for the actual results of the interaction or list operations such as applying an index:

, and the 3.0 dictionary still has its own iterator, which returns a contiguous key, so there's no need to call keys directly in this context:

。 Since keys no longer returns a list, the traditional encoding pattern for scanning a dictionary by the sort key is no longer valid in 3.0, instead, first using a list call to convert the keys view, or using sorted on a key view or the dictionary itself:

17, in the 20 chapter has more introduction, 29 chapters also have, later will see: A, using yield statement, user-defined function can be converted to an iterative generator function; b, when written in parentheses, the list resolution transformation becomes an iterative generator expression; c, user-defined classes pass __iter_ _ or __getitem__ operator overloading becomes iterative.

Vi. documentation (chapter 15th)

This section describes: A, the design of the Python grammar model, B, for those who want to understand the Python toolset of the reader resources. As shown in the table below, Python information can be found in many places and is gradually increasing, as the document is an important tool in practical programming:

1. Document strings are for documents with larger functionality, while # comments are for smaller-featured documents.

2. The dir built-in function is a simple way to grab a list of all the properties available within an object, and it can invoke any object with attributes. For example >>>import sys;>>>dir (SYS), to find out which properties are provided by the built-in object type, run Dir and pass in the output of the desired type, such as >>>dir ([]). The dir result of any built-in type contains a set of properties that are related to the implementation of the type, with double underscores at the beginning and end, to ensure uniqueness. and Dir (str) ==dir ("); dir (list) ==dir (" ").

3. In addition to ¥ annotations, Python supports documents that can be automatically attached to objects and remains viewable at run time. Syntactically, such annotations are written out of a string, placed at the top of a module file, function, and class statement, and before any executable code, Python automatically encapsulates the string, which is called a document string, making it the __doc__ property of the corresponding object. A, for example, the following file, its document string appears at the beginning of the file and the beginning of the function and the class, where the file and function of the multi-sweat annotation using Sanchong quotation block string, but any type of string can be used: The following diagram, the focus of the document agreement is that the note will be saved in the __doc__ property for viewing. So, to display this module and the document string that its object intends to associate, we just need to import the file and simply print its __doc__ property:

PS: It is generally necessary to explicitly say the document string to be printed, otherwise you will get a single string with a newline character embedded in it.

4. View the built-in document string >>>import sys;>>>print (sys.__doc__); >>>print (sys.getrefcount.__doc__); >>print (int.__doc__); however, it is not necessary to do so, or to recommend the Help method.

5, the common trap of writing code: A, colon; b, starting from the 1th sweat, the top program code starts from the first line; C, blank lines are important at the interactive mode prompt; D, indentation is consistent; E, do not write C code in Python; F, use a simple for loop instead of while or range G, pay attention to the variable object in the assignment statement; H, do not expect the function that modifies the object in the same place to return the result; I, be sure to call the function with parentheses, such as File.close (); J, do not use extensions or paths in import and overloading, write import mod instead of import mod.py.

Statement and Grammar of the python2.3-principle

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: