0. Preface
The most important homework for learning a language is practice and review. Although I didn't teach you anything in section 37th of the stupid methodology Python, it reminds us: "I 've learned so much, how much do you remember? I have reviewed it !"
Next we will review the first part of this section "keywords:
Keywords in Python include:
And del from not while as elif global or with assert else if pass yield break doesn't import print class exec in raise continue finally is return def for lambda try
What keywords do you want to see? OK. Open a terminal like this ~
Long @ zhouyl :~ $ Python
Python 2.7.3 (default, Jan 2 2013, 16:53:07)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> Import keyword
>>> Keyword. kwlist
['And', 'as', 'assert ', 'Break', 'class', 'contine', 'def', 'del ', 'elif ', 'else', 'Got t', 'exec ', 'Finally', 'for ', 'from', 'global', 'if', 'import', 'in ', 'Is ', 'lambda', 'not ',' or ', 'pass', 'print', 'raise ', 'Return', 'try', 'while ', 'with', 'yield ']
>>>
================================ Gorgeous text separator ======== ========================================
How many other keywords do you remember? You may wish to compare and think about its usage one by one. The following is my summary. Based on the previous study notes, I divided the above keywords into the following categories:
1. Judgment and loop
The loop and judgment of Python mainly include the following keywords:
If elif else for while break continue and or is not in
These keywords are introduced in the if syntax, while syntax, for syntax, and... or syntax. The following is a reference:
1.1 if syntax
The if syntax is very similar to the C language and shell script. The biggest difference is the colon and strict indentation. Of course, these two points are also the difference between Python and other languages:
If condition1:
Do something
Elif condition2:
Do another thing
Else:
Also do something
1.2 while syntax
The while Syntax of Python is different from the while syntax in C and shell. Besides the colon and indentation, The while syntax can carry an optional else statement:
While condition:
Do something
Else:
Do something
Note: The else statement is optional, but when using the while statement, be sure to determine that the statement can jump out!
1.3 for syntax
Similar to while, Python's for loop also includes an optional else Statement (executed when the for loop exists, but the code in the else statement block is not executed if the break statement exists !), In addition, the for keyword in constitutes the most common list resolution usage (a special blog will be written later ).
The general usage of for is as follows:
For I in range (1, 10, 2 ):
Do something
If condition:
Break
Else:
Do something
For list parsing usage:
For items in list:
Print items
1.4 and... or syntax
Different from other languages, the and/or operation of Python returns one of the two values involved in the judgment. Therefore, we can use this feature to implement? B: c!
If you have a C language, you know "? B: c! "Syntax: Judge a. If it is correct, execute B; otherwise, execute c!
In Python, we can use "a and B or c" (This method must ensure that B must be a True value). In python, execute this sentence from left to right and First Judge a and B: if a is a True value, the and B statement still needs to execute B, and B is a True value at this time! Therefore, the value of a and B is B, and a and B or c becomes B or c. Because B is True, the result of B or c is B; if a is a False value, the result of Statement a and B is a. In this case, a and B or c is converted to a or c, because a is a False value, so whether c is True or Flase, the result of a or c is c !!! If the logic is passed, Is a and B or c a in Python? B: c! Usage?
1.5 is, not
Is and is not are keywords for determining the same identity in Python. They are usually used to determine whether they are True, False, or None (NULL in Python )!
For example, if alue is True :...
(Do not remember the penalty review for children's shoes in this section: python study Note 2 -- judgment Statement)
2. Functions, modules, and classes
For Python functions and modules, the following keywords are used:
From import as def pass lambda return class
So do you still remember them? The following is a brief introduction:
Module 2.1
Python programming usually uses a large number of modules in the standard library, using the import, from, and as keywords.
For example: import sys # import sys module
From sys import argv # import argv from sys module, which is used in the previous introduction to parameter passing through the script
Import cPickle as p # import the cPickle module and name it p here. Then, you can directly use p to replace the original name of the cPickle module, which is used in the memory when introducing file input and output.
2.2 Functions
When defining a function in Python, the def keyword is used. If you do not want to write real function operations, you can use the pass keyword to indicate that no operation is performed:
Def JustAFunction:
Pass
Of course, the return keyword is used when you need to return values to the function. Here, we can briefly mention that the function return values in Python can be multiple (when receiving the return values, we can use the corresponding number of variables to receive them !)!
In addition, there is a magic Lambda function in Python, which allows you to define the smallest function of a single row, which is borrowed from Lisp and can be used in any function. For example:
G = lambda x: x * 2 # define a Lambda function to calculate twice the parameter and return it!
Print g (2) # when using the variable returned by the lambda function as the function name, you just need to include the corresponding parameter in the brackets!
(I do not remember the penalty review for my children's shoes in this section: python Study Notes 4-functions)
3. Exceptions
Exceptions in Python mainly include the following keywords:
Try again t finally raise
The exception section is relatively simple. place possible exceptions in the statement block following try, use the distinct T keyword to capture certain exceptions and perform corresponding operations in the subsequent statement blocks. In finally, no matter what exceptions occur, the finally statement is always executed at the end of the execution: subsequent statement blocks (such as closing files and other necessary operations !)
The raise keyword causes an exception under certain conditions. It is usually used in combination with custom exception types.
(Do not remember the penalty review for children's shoes in this section: python study Note 6 -- Exception Handling)
4. Miscellaneous
After the above three types, there are still these keywords:
Print del global with assert yield exec
First, you can see print in the previous notes or any place, so you are still familiar with it. I will not discuss it here!
The del keyword is already involved in the previous note. For example, to delete an item in the list, we use "del mylist [0]".
You may be unfamiliar with the remaining keywords, so we will introduce them below:
4.1.global keywords
When you declare variables in the function definition, they have no relationship with other variables with the same name outside the function, that is, the variable name is local for the function. This is called the scope of a variable. The scope of all variables is the block they are defined, starting from the point where their names are defined.
Eg.
#!/usr/bin/python# Filename: func_local.pydef func(x): print 'x is', x x = 2 print 'Changed local x to', xx = 50func(x)print 'x is still', x
The running result is as follows:
$ Python func_local.pyx is 50 # print the value of x when running the func function. The value is the value of 50, which is defined externally as the parameter, so we can print x = 50 Changed local x to 2 # assign x to 2 in the func function, and print x is still 50 # print the value of x after running the func function, at this time, the value of x is still the 50 previously assigned, instead of the 2 modified in the func function, because only the local variables in the function are modified.
So why do we need to mention local variables here? Bingo, you can guess that this global is used to define global variables. That is to say, if you want to assign a value to a variable defined outside the function, you have to tell Python that the variable name is not local, but global. We use the global statement to complete this function. Without a global statement, it is impossible to assign values to variables defined outside the function.
Eg.
#!/usr/bin/python# Filename: func_global.pydef func(): global x print 'x is', x x = 2 print 'Changed local x to', xx = 50func()print 'Value of x is', x
The running result is as follows:
$ Python func_global.pyx is 50 Changed global x to 2 Value of x is 2 # The global statement is used to declare that x is global. Therefore, when we assign the value to x in the function, this change is also reflected when we use the value of x in the main block.
You can use the same global statement to specify multiple global variables. For example, global x, y, and z.
4.2.with keywords
Some tasks may need to be configured in advance and cleaned up afterwards. In this scenario, the with statement of Python provides a very convenient processing method. A good example is File Processing. You need to obtain a file handle, read data from the file, and then close the file handle.
If you do not need the with statement, the code for opening a file and reading the file is as follows:
file = open("/tmp/foo.txt")data = file.read()file.close()
Of course, there are two problems to open the file directly: first, you may forget to close the file handle; second, an exception occurs in File Reading data without any processing. The exception handling version is added as follows:
file = open("/tmp/foo.txt")try: data = file.read()finally: file.close()
Although this code runs well, it is too redundant. At this time, it is time to show your skills. In addition to more elegant syntaxes, with can also handle exceptions in the context. The code for the with version is as follows:
with open("/tmp/foo.txt") as file: data = file.read()
This seems to be full of magic, but it is not just magic. Python is still very clever in handling. The basic idea is that the object with the value must have a _ enter _ () method and a _ exit _ () method.
The execution logic of the with statement is as follows: after the statement followed by with is evaluated, the _ enter _ () method of the returned object is called, the return value of this method is assigned to the variable after. After all the code blocks after with are executed, the _ exit _ () method of the returned object is called.
The following example illustrates how with works:
#!/usr/bin/python# with_example01.py class Sample: def __enter__(self): print "In __enter__()" return "Foo" def __exit__(self, type, value, trace): print "In __exit__()" def get_sample(): return Sample() with get_sample() as sample: print "sample:", sample
Run the code and output the following code:
$ Python with_example01.py In _ enter _ () # _ enter _ () method executed sample: Foo # _ enter __() value returned by the method-in this example, it is "Foo" and is assigned to the variable 'sample' to execute the code block, the printed variable "sample" has a value of "Foo" In _ exit _ () # _ exit _ (). The method is called.
4.3.assert keywords
An assert statement is a convenient way to insert a debugging breakpoint to a program. The assert statement is used to declare that a condition is true. When the assert statement fails, an AssertionError occurs. Therefore, we can use try... retry t to handle this exception.
Eg.
>>> Mylist # in this case, mylist has a list of three elements.
['A', 'B', 'C']
>>> Assert len (mylist) is not None # Use assert to judge whether the list is not empty. If yes, no result is returned.
>>> Assert len (mylist) is None # Use assert to judge whether the list is empty.
Traceback (most recent call last ):
File" ", Line 1, in
AssertionError # AssertionError thrown
4.4.yield keywords
Let's first look at an example:
def fab(max): n, a, b = 0, 0, 1 while n < max: yield b # print b a, b = b, a + b n = n + 1 '''
Use this function:
>>> for n in fab(5): ... print n ... 1 1 2 3 5
In short, yield is used to convert a function into a generator. A function with yield is no longer a common function. The Python interpreter regards it as a generator, calling fab (5) does not execute the fab function, but returns an iterable object! During for loop execution, code in the fab function is executed in each loop. When yield B is executed, the fab function returns an iteration value. During the next iteration, the Code continues to run from the next statement of yield B, and the local variable of the function looks exactly the same as before the last interrupted execution, so the function continues to run until yield is encountered again.
You can also manually call the next () method of fab (5) (because fab (5) is a generator object and this object has the next () method ), in this way, we can see the fab execution process more clearly:
>>> f = fab(5) >>> f.next() 1 >>> f.next() 1 >>> f.next() 2 >>> f.next() 3 >>> f.next() 5 >>> f.next() Traceback (most recent call last): File "
", line 1, in
StopIteration
When the function execution ends, generator automatically throws a StopIteration exception, indicating that the iteration is complete. In a for loop, the loop ends normally without handling the StopIteration exception.
We can draw the following conclusions:
A function with yield is a generator, which is different from a common function. Generating a generator looks like a function call, but does not execute any function code until it calls next () (next () is automatically called in the for loop to start execution. Although the execution process is still executed according to the function process, every execution of a yield statement is interrupted and an iteration value is returned. The next statement of yield continues to be executed during the next execution. It seems that a function is interrupted several times by yield during normal execution, and the current iteration value is returned through yield for each interruption.
The advantage of yield is obvious. By Rewriting a function as a generator, the iteration capability is achieved. Compared to calculating the next () value by using the Instance Storage status of the class, the Code is not only concise, the execution process is clear.
Note: If you haven't understood yield after reading this section, it's okay, because yield is a difficult problem for beginners. What you need to do next is ...... Take a look at the yield blog in the following references!
4.5.exec keyword
The official document explains exec: "This statement supports dynamic execution of Python code." That is to say, you can use exec to dynamically execute Python code (or file ).
>>> Longer = "print \" Hello World, my name is longer \ "" # For example, we have defined a string >>> longer 'print "Hello World, my name is longer "'>>> exec (longer) # Use exec to dynamically execute the code Hello World, my name is longer >>> exec (sayhi) # Open the file name directly using exec (specify sayhi, sayhi. py and "sayhi. py "always reports certain errors, but I think it is very typical to directly report errors with sayhi) Traceback (most recent call last): File"
", Line 1, in
TypeError: exec: arg 1 must be a string, file, or code object # error reported by python IDE, the first parameter of exec must be a string, file, or code object >>> f = file ("sayhi. py ") # use file to open sayhi. py and create f instance >>> exec (f) # Run the file descriptor f directly using exec. The operation is normal !! Hi, this is [''] script
The example given above is relatively simple. Note that the exec statement usage in this example is different from that of eval_r () and execfile. exec is a keyword (otherwise, how can I introduce it here ~~~), Eval_r () and execfile () are built-in functions.