preface
Recently, I had some trouble learning Java Sockst, and I felt that I needed to relearn Python as a scripting language. I found a good book about learning Python, “Learning Python the Stupid Way,” and decided to spend a long time relearning Python. Put some of your summary experience and accumulation of some things on the blog, we can learn from each other to discuss… I hope you can put forward the deficiencies, AND I will add and delete them appropriately… Improve the paper
The body of the
Python2.7 keyword and summary:
and | del | from | not | while | as | elif |
global | or | with | assert | else | if | pass |
yield | break | except | import | class | exec | |
in | raise | continue | finally | is | return | def |
for | lambda | try |
Total: 31. Note: if you want to run the code I wrote on your own computer, add it to the first line
#coding: UTF-8 because I have Chinese in my output
(1) And (2)
2. Del: Used for list operations to delete one or more consecutive elements.
3. From: Import the corresponding module with import or from… import
4. Not: indicates logical ‘not’
5. While: A while loop that allows a statement to be executed repeatedly. Used in the case of an infinite loop. The following is an example:
While Ture: if a > b: add() Retype!"Copy the code
6. As: with…. As instead of the traditional try… Finally syntax.
The basic idea is that the object with asks for a value must have an __enter__() method and an __exit__() method.
After the statement immediately following with is evaluated, the __enter__() method of the return object is called, and the return value of this method is assigned to the variable following AS. When all the code blocks following with have been executed, the previous __exit__() method that returns the object is called. The following is an example:
1 class Sample:
2 def __enter__(self):
3 print "In __enter__()"
4 return "Foo"
5
6 def __exit__(self, type, value, trace):
7 print "In __exit__()"
8
9
10 def get_sample():
11 return Sample()
12
13
14 with get_sample() as sample:
15 print "sample:", sample
Copy the code
Output result:
In __enter__()
sample: Foo
In __exit__()
Copy the code
Step 1: the __enter__() method is executed
Step 2: The value returned by the __enter__() method – in this case “Foo”, assigned to the variable ‘sample’
Step 3: Execute the code block and print the variable “sample” with a value of “Foo”
Step 4: The __exit__() method is called. The real power of with is that it can handle exceptions. You may have noticed that the __exit__ method of the Sample class takes three arguments – val, type, and trace. These parameters are quite useful in exception handling.
Elif: Used in conjunction with if, a branch of an if statement is represented by elif.
If you want to reassign a value to a global variable, you need to global it. Now I want to set the value of the global variable), and then reassign. The following is an example:
1 # coding: utf-8 2 # # # # # # # # # # # # # # # # # 3 # # # # # # # # # # # # # # # # # # 4 familiar with global 5 # define global variables, Def get_NAME(): 9 def get_NAME(): 9 def get_NAME(): 9 def get_NAME(): 9 def get_NAME(): 9 def get_NAME(): 9 def get_NAME(): 9 def get_NAME(): 9 def get_NAME(): 9 def get_NAME(): 9 def get_NAME(): 9 def get_NAME(): 10 12 global NAME 13 NAME = name_value 14 print u",get_NAME() 15 new_name = "521xueweihan" 16 Print u" print NMAE ",get_NAME()Copy the code
Output result: \
Xueweihan (NAME, xueweihan); NMAE (521xueweihan)Copy the code
9. Or: it’s a logical thing to say.
E.g. Please see as, with as, above!
11. Assert: Indicates an assertion (asserting that a condition is true and throwing an exception if the assertion is false) used to declare that a condition is true and to raise an exception if the condition is not true: AssertionError
12. Else: Look at the explanation below if
13. If: The if statement is used to select the branch, which block to execute according to the condition. (It is best not to have nested if statements in an if statement. You can write nested if statements in another function.)
if a > b:
print "a > b
elif a < b:
print "a < b"
else:
print "a = b"
Copy the code
14. Pass: Pass means to do nothing. Purpose and Understanding: When we write a software framework, we do not write specific methods, classes and so on, waiting for the follow-up work to be done. Add pass to methods and classes so that they compile without errors! Something like this:
Error: expected indented block test_pass() def test_pass():passCopy the code
15. Yield: Used much like a return, but returns a generator. I’m not saying this very graphically. I’ll focus on yield in Python in the next section, but look at the following code first:
1 def test_yield(n): 3 for I in range(n): 4 for j in test_yield(8): 4 for j in test_yield(8): 5 ########## 11 def fab(Max): 12 a,b = 0,1 while a < Max: 14 yield a 15 a, b = b, a+b 17 for i in fab(20): 18 print i,",",Copy the code
Output result:
0:2:4:6:8:10:12:14: Yield Fibonacci sequence! 0, 1, 1, 2, 3, 5, 8, 13,Copy the code
16. Break: the function is to terminate the loop, the program to break the place is the end of the loop. Note: If the for or while loop terminates (break), the else statement does not execute.
17. Except: Used with a try to catch exceptions.
- try:
- block
- Except [exception, [data…]] :
- block
- try:
- block
- except [exception,[data…]]:
- block
- else:
- block
The syntax of this Python exception handling is as follows: ◆ Execute a statement under try. If an exception is raised, execution will skip to the first except statement. ◆ If the exception defined in the first EXCEPT matches the exception raised, the statement in that EXCEPT is executed. ◆ If the exception raised does not match the first except, the second except will be searched. There is no limit to the number of except that can be written. ◆ If all except do not match, the exception is passed to the highest-level try code that calls this code. ◆ If no exception occurs, else block code is executed.
The first format:
Except try: num = 5/0 except: print uCopy the code
The second:
1 try: 2 f = open("file.txt","r") 5 Print e #Copy the code
Output result:
Calculation error IO error! [Errno 2] No such file or directory: 'file.txt'Copy the code
18. Import: Used to import modules, sometimes from…. import
19. Print: output
Class: Defines a class
21EXEC: Exec statements are used to execute Python statements stored in strings or files. You can generate a string containing Python code and then execute the statements using exec statements.
22. In: Finds if the list contains an element, or if string A contains string B. Note that you cannot check whether list1 contains list2. The code is as follows:
In 2 first_list = [1, 2] 3 second_list = [1, 2, 3] 4 element = 1 5 red = 'red' 6 red_clothes = "red clothes" 7 8 print red in red_clothes #true 9 print first_list in second_list #false 10 print element in first_list #trueCopy the code
The output is:
True
False
True
Copy the code
23. Raise: Raise can explicitly raise an exception. Once the raise statement is executed, the following code is not executed
# understand raise try: raise IOError # Raise a custom error class. That's called a custom exception print u" Do I run it?" Except IOError: print "IOError test raise"Copy the code
The following output is displayed:
IOError test raise
Copy the code
24. Continue: Skip statements in the loop block following continue and continue to the next loop.
25. Finally: When you see a finally statement, you must execute a block of code that finally statements.
To summarize python exceptions, see the following code:
One:
F = open(' XXX ') 4 do something 5 except: 6 do something 7 finally: 8 f.close()Copy the code
Two:
1 try:
2 f = open('xxx')
3 except:
4 print 'fail to open'
5 exit(-1)
6 try:
7 do something
8 except:
9 do something
10 finally:
11 f.close()
Copy the code
The reason we write finally is that the file cannot be closed if the program throws an exception, but the file must be closed if it is already open. In the first error code, if the exception occurs when f=open(‘ XXX ‘), such as if the file does not exist, it is immediately clear that executing f.close() makes no sense. The corrected solution is the second piece of code.
26. Is: An object in Python contains three elements: ID, type, and value
Id is used to uniquely identify an object, type is the type of the object, and value is the value of the object
Is determines whether object A is object B based on its ID == Whether the value of object A is equal to that of object B based on its value
E = 1, es = 1.0, ess = 1, ess = 1.0, ess = 1, ess = 1.0, ess = 1.0, ess = 1.0, ess = 1.0, ess = 1.0, ess = 1.0, ess = 1.0, ess = 1.0, ess = 1.0, ess = 1.0, ess = 1.0, ess = 1.0, ess = 1.0 "" 7 print id(e) 8 print id(es) 9 print id(ess)Copy the code
27. Return: Used to exit a function or return a value at the same time.
28. Def: used to define methods
29. The for: for… Use in together: It recurses over a sequence of objects, traversing each item in the queue
Lambda: anonymous function, don’t think of a name for the function. Improved code simplicity. Such as:
1 print g = lambda :"lambda test." 2 print g() = lambda x, y=1:x + y Print num1(10,10) print num1(10,10) print num1(10,10)Copy the code
Output result:
lambda test.
2
20
Copy the code
31. Try: Occurs in the exception handling format: try… Except, try holds the statement you want to execute, except catches exceptions
So far, this paper has given a brief overview of all 31 keywords. In the following articles, I will give a detailed explanation and understanding of some important keywords. I will also try my best to further understand the concepts in the book, hoping to summarize better articles and share them with you. \