-python Common Keywords and, Del, from, not, while, as, elif, Global, or, with, assert, else, if, pass, yield, break, except, import , print, class, Exec, in, raise, CONTIUE, finally, was, return, Def, for, Lambda, Try-1.and, or and, or as a logical term, Python has a short Path logic, FALSE and returns false does not execute subsequent statements, true or returns true immediately, does not execute subsequent statement -2.del delete variable if __name__== ' __main__ ': A=1 # object 1 is referenced by variable a , the reference counter for object 1 is 1 B=a # object 1 is referenced by the variable B, the reference counter of object 1 is incremented by 1 c=a #1对象1 is referenced by the variable C, the reference counter of Object 1 is added 1 del a #删除变量a, and a reference to 1 is lifted. El b #删除变量b, de-reference B to 1 #print a #运行此句出错, name ' A ' is not defined, Description del delete variable a print (c) #最终变量c仍然引用1 print C and list itself contains a variable, for example: List = [1,2,3]# contains list[0],list[1],list[2]# does not contain a number, so if __name__== ' __main__ ': li=[1,2,3,4,5] #列表本身不包含数据 1,2,3,4,5, but contains variables: li[0] li[1] li[2] li[3] li[4] first=li[0] #拷贝列表, there will not be a copy of the data object, but instead create a new variable reference del li[0] # The list itself contains variables , Del deletes the variable. Print Li #输出 [2, 3, 4, 5] print (first) #输出 13.from from reference module, example: from sys import argv# importing from sys argvfrom SYS import *# will be in SYSEverything is imported into the import SYS # importing SYS, and when the content in SYS is required, SYS.ARGV and from sys import * #不用每次都重复输入 ' sys. ' 4.golbal Golbal is a global variable, but when the same variable name appears in a single function, the local variable golbal QQ = 66print "q=" in a single function, q #q = 66def function (): q = 3 print ' q = ' , Qfunction () # q = 3print ' q = ', Q # q = 665.with with is used to handle exception # do not use with file exception = open ("/tmp/foo.txt") Try:data = file. Read () Finally:file.close () # with WithWith open ("/tmp/foo.txt") as File:data = File.read () immediately after the statement with the following is evaluated, returns the object's Enter () party Method is called, the return value of this method will be assigned to the variable following the as, where file is called when the block with the code behind it is all executed, the exit () method of the previous return object will be invoked #with's work 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#1. The __enter__ () method is executed. The value returned by the __enter__ () method-In this case, "Foo"-is assigned to the variable ' sample ' #3. Executes the code block, printing the variable "sample" with the value "Foo" #4. The __exit__ () method is called #with really powerful is that it can handle exceptions. #可能你已经注意到Sample类的__exit__方法有三个参数-val, type, and trace. #这些参数在异常处理中相当有用. Class SampLe:def __enter__ (self): return self def __exit__ (self, type, value, trace): print "type:", type Print "Value:", Value print "Trace:", Trace def do_something (self): bar = 1/0 return bar + 10wit H Sample () as sample:sample.do_something () in fact, the exit () method is executed when any exception is thrown in the code block following the with. As the example shows, when an exception is thrown, the associated type,value and stack trace is passed to the exit () method, so the thrown Zerodivisionerror exception is printed. When you develop a library, clean up resources, close files, and so on, all in the exit method. -6.while, for...in ... Are circular statements, use while to be aware of conditions, to prevent falling into the dead loop for in traversal -7.assert assertion, declare its Boolean value must be true judgment, if an exception occurs, the expression is false. You can understand that the Assert assertion statement is Raise-if-not, which is used to test the expression, and its return value is false, triggering an exception. Assert 1==1assert 1 = = will error Asserterrorassert expression, ' arguments ' #assert expressions [, parameters] to explain assertions and better know where the wrong 8.pass pass is an empty statement, In order to ensure the integrity of the program structure, pass does not do anything, generally used as a placeholder statement when you write a program part of the content is not ready, can be used to take the PASS statement def No_idea (): pass# instance for letter in ' Python ': if-letter = = ' h ': Pass print U ' This is the pass block ' Print U ' current letter: ', Letterprint ' bye,bye ' -9.yield yield means production, returns a generator object, each generator only Can be used once def h (): print ' to be brave 'Yield 5h () #看到某个函数包含了yield, which means that this function is already a generator# call H () function, the print statement is not executed, and the yield is executed. Next () method Def h (): print ' Wen Chuan ' Yield 5 print ' fighting! ' c = h () # >>>c.next () # in the IDE without print C.next (), direct c.next (). The # Next () Statement resumes generator execution, and until the next yield expression # Wen Chuan # 5 # When you run C.next again () because there is no yield error # >>>c.next () # fighting # T Raceback (most recent): # File '/home/evergreen/codes/yidld.py ', line one, in <module># C.next () # Stopite Ration a function with yield is a generation, unlike a normal function, which generates a generator that looks like a function call, but does not execute any function code until it is called. Next () (in the For Loop, the next () is automatically called ) to begin execution although the execution process still executes according to the function's process, each execution to a yield statement is interrupted and an iteration value is returned, and the next execution proceeds from the next statement of yield. It looks as if a function was interrupted several times by yield during normal execution, and each break returns the current iteration value through yield. #使用isgeneratorfunction判断一个函数是否是一个特殊的generator function from inspect import isgeneratorfunction isgeneratorfunction (h) # Truesend () and Next () def h (): print ' Wen Chuan ', M = Yield 5 # fighting! Print m d = yield print ' We are together! ' c = h () m = C.next () #m Gets the yield 5 parameter value 5d = C.send(' fighting! ') #d obtained the yield 12 parameter value 12print ' We will never forget the date ', M, '. ', D#send () can pass the value of the yield expression in, and next () cannot pass a specific value, only pass none in. #因此, we can be seen as C.next () and C.send (None) as a function of # NOTE!!! On the first call, use the next () statement or send (None), you cannot send a value that is not None using send, otherwise it will go wrong because there is no yield statement to receive this value -10.break and Contiue Python The break statement terminates the loop and is used in the while and for loops!! Jumping directly out of the entire loop nesting loop, the break statement stops executing the deepest loop and starts executing the next line of code for the ' Python ': # The first example of if letter = = ' h ' break print U ' when Period Letter: ', letter# output to ' P ' y ' t ' var= 10 # Second example while var > 0:print u ' current letter: ', var var = var-1 if var = = 5 break# output to 6 print ' bye ' break is jumping out of the entire loop, continue is jumping out of the current loop # example 1for letter in ' Pyhton ': if letter = = ' h ': continue Print U ' current letter: ', letter# prints out pyton# example 2var = 10while var > 0:var-= 1 if var = 5:continue print U ' current letter: ', var# result 98764321-11.try except finallytry:< statement > #运行别的代码except < name >:< statement > #如果在try部份引发了 ' name ' Exception except < name >,< data >:< statement > #如果引发了 ' name ' exception, get additional data else:< statement > #如果没有异常发生如果当try后的语句执行时发生异常, Python jumps back to try and executes the first except clause that matches the exception, and the control flow passes through the entire try statement (unless a new exception is thrown when the exception is handled). If an exception occurs in the statement after the try, but there is no matching except clause, the exception will be submitted to the upper try, or to the top of the program (This will end the program and print the default error message). If no exception occurs when the TRY clause executes, Python executes the statement after the Else statement (if there is else), and then the control flow passes through the entire try statement. Try:try:raise Nameerror except Typeerror:print ' as ' except Nameerror:print ' E ' # e,try after statement raise Trigger XOR Often, except has no matching words, is thrown to the upper try match, print ' E ' try:1/0except Exception, E:print e #以上传统的异常处理, Join!!! Detailed error messages will be printed after Traceback import tracebacktry:1/0except Exception:traceback.print_exc () < statements >finally:< Statements & Gt #退出try时总会执行raisetry: 1/0except Exception as E: "' Exception of the parent class that can catch all exceptions ' ' print ' 0 cannot be removed ' else: ' ' protect code that does not throw exception ' Print "no exception" Finally:print "finally always executes my" -12.raise trigger exception raise [Exception[,args[,traceback]] statement Exception is the type of exception (for example, Nameerror) parameter is an exception parameter value. This parameter is optional and if not provided, the exception parameter is "None". The last parameter is optional (rarely used in practice) and, if present, is the tracking exception object. def mye: If level < 1:raise Exception ("InvAlid level! ", level) raise after the exception is triggered, the following code will no longer execute try:s = None if S is None:print" s is empty object "raise Nameer Ror #如果引发NameError异常, the following code will not be able to execute the print Len (s) #这句不会执行, but the subsequent except will still go to except Typeerror:print "empty object has no length" #由于错误类 Type is not TypeError, do not execute printtry:s = None if s none:print u "s is empty object" raise Nameerror (' name is wrong ', ' is ') #如果引发NameError异常, the following code will not be able to execute the print Len (s) #这句不会执行, but the subsequent except will still go to except Nameerror,argvment:print u "empty object No Length ", argvments = Noneif S is none:raise nameerror print ' are here? ' #如果不使用try ... except this form, then directly throwing an exception, will not execute to here def mye ( Level): If level < 1:raise Exception ("Invalid level!", level) # After the exception is triggered, the subsequent code will no longer execute Try:mye (0) # Trigger exception except "Invalid level!": Print 1else:print 2die function, printing error message def die (error_massage): Raise Exceptio N (error_massage) a = ' wer ' if a = = None:print ' None ' Else:die () -13.exec–eval–execfile exec is used to execute Python statements stored in a string or file ex The EC is a statement that treats the string str as valid PythoN code to perform eval with execfile is the Pytho built-in function eval (Str[globals[locals]) function evaluates the string str as a valid Python expression and provides the return computed value exec ' print ' Hello World "' EXEC ' a=100 ' # Executes a = 100print a #100eval (' 3+5 ') # 8b = eval (' 5+6 ') #eval returns the computed value of the print B + 1 #12execfile (filename) function can be used To execute file execfile (r ' F:\learn\ex1.py ') # If you are in the directory where the file is located directly execute execfile (R ' ex1.py ') from Os.path Import exists exists (file) The filename string as a parameter, if the file exists returns true, otherwise returns False-14.return return is the function return value def fun (): The print ' ASD ' # fun () function does not show return, by default returns NONEDEF Fan (a ): Return a# Returns a value -15.lambda-filter-map-reduce-lambda is just an expression that defines an anonymous function that acts as a function sketch because Lambda is just an expression that can be used directly as a python A member of a list or Python dictionary, such as info = [Lambda a:a**3, lambda b:b**3]g = lambda x:x+1g (1) #2 equivalent to Lambda x:x+1 (1) G (3) #4 # where x is the entry parameter, x+1 The function used for function body # also represents the Def g (x): Return X+1#LAMBDA can also be used in functions def action (x): return lambda Y:x+ya = action (3) # A is the return value of the action function, a ( #, A (22), called the lambda expression returned by the action # The above function can also be written directly below B = lambda X:lambda Y:x+ya = B (3) A (2) # can also be directly (b (3)) (2) # lambda can be one, multiple Parameter G = lambda x:x*2 #oneprint g (3) m = lambda x, y, Z: (x-y) *z # Mutipleprint m (3,1,2) #lambda does not increase the efficiency of the program, only makes the code more concise. #如果可以使用for ... If to complete, be resolute without lambda. #如果使用lambda, do not include loops within lambda, and if so, I would rather define functions to complete, #使代码获得可重用性和更好的可读性. # Lambda exists to reduce the definition of a single-line function. #--filter (function or None, sequence)-list, tuple, or string# functions is a predicate function that takes a parameter that returns a Boolean value of TRUE or false. # The filter function calls the function function for each element in the sequence parameter sequence, # finally returns the type of the # return value with the result of true and the type of the parameter sequence (list, tuple, string) of the same foo = [2, 18, 9 , +, 8, 27]print filter (lambda x:x% 3 = = 0, foo) # filter is the filter/filter function print[x for x in foo if x% 3==0] #[18, 9, 24, 12, 27] Select the map (function, sequence) in Foo that can be divisible by 3 to execute function on item in sequence, and make the execution result list returns a single parameter str = [' A ', ' B ', ' C ', ' d def fun2 (s): return S + ". txt" ret = map (fun2, str) PRINT ret # [' A.txt ', ' b.txt ', ' c.txt ', ' d.txt '] multiple parameters, requires the function to accept multiple parameters de F Add (x, y): Return x+yprint Map (Add,range (5), Range (5)) #[0,2,4,6,8]foo = [2,, 9,,, 8,, 27]print map (lamb Da x:x * 2 + ten, foo) #[14,------------------64]reduce (function, sequence, starting_value) to SequenThe item order in the CE iterates over the call function, and if there is a starting_value, it can also be called as an initial value, for example to add Def add1 (x, y) to the list: return x+yprint reduce (Add1,range ( 1,100) # 4950 Note: 1+2+...+99print Reduce (add1,range (1,100), 20) # 4970 Note: 1+2+...+99+20,20 is the initial value
Python keywords and their usage