Beginner Python (ix)--function
Beginner Python, mainly finishing some of the learning points, this is the function.
function definition:
#-*-coding:utf-8-*- #definition of a functiondefmy_function (x):ifX>0:returnxelifx<0:return-xElse: Pass #Call to functionA = my_function (-1) b= My_function (2) C=my_function (0)PrintA,b,c#null function, pass as placeholderdefempty_function (x):Pass PrintEmpty_function (-1) #parameter check, add parameter check to my_function functiondefmy_function (x):if notisinstance (x, (Int,float)):#raise equivalent to throw in Java, throws an exception RaiseTypeError ('Unexpectedtype') elifx>=0:returnxElse: return-xPrintMy_function (1) PrintMy_function (-1) #Print my_function (' a ')#returns multiple values, cow er forcedefmulti_function (x): X0= X+1X1= X-1#The return is actually a tuple returnx0,x1PrintMulti_function (2)
Parameters:
#-*-coding:utf-8-*- " "' default parameter: When you do not specify a value for this parameter, the parameter has a default value" " defDefault_para (x,n=2,s=3): returnx*n*sPrintDefault_para (2) PrintDefault_para (2,3) PrintDefault_para (2,n=5) PrintDefault_para (2,s=3) PrintDefault_para (2,n=2,s=4) #sinkholedefDefault_para_hole (l=[]): L.append ('Itfootballclub') returnLPrintDefault_para_hole ()PrintDefault_para_hole ()" "The first time for [' Itfootballclub '] The second pass is [' Itfootballclub ', ' itfootballclub '] The problem is that the value of L has already indicated the object when the function is defined, and if you do not specify the argument, he points to the object by default. If the object changes, the value of the default parameter will change so try to use the immutable object [] to None" " #go to the sinkhole version, none for immutable objectsdefDefault_para_no_hole (l=None):ifL isnone:l=[] L.append ('Itfootballclub') returnLPrintDefault_para_no_hole ()PrintDefault_para_no_hole ()" "' variable parameter: means that the number of arguments is 0. N-A" " #multiple parameters can be passed without variable parameters, using list and tupledefChangeable_para (Multi): Sum=0 forNinchMulti:sum+=Nreturnsum#0PrintChangeable_para ([])#ListPrintChangeable_para ([1,2,3,4,5]) #tuplePrintChangeable_para ((1,2,3,4)) " "the "Above" method can also be achieved by passing in 0. N parameters are passed, but need to be implemented to assemble as list or tuple if you have a list or a tuple, it's understandable if you don't want to assemble every time, you can use variable parameters" " #modified version, variable parameter is to add an asterisk (*) before the parameter, so easydefChangeable_para_update (*multi): Sum=0 forNinchMulti:sum+=NreturnsumPrintChangeable_para_update (A) #If you have a list, variable parameters can also be fusedname = [1,3,4,7,9] PrintChangeable_para_update (*name)#isn't that a lot sharper? " "' keyword parameter: pass 0...N parameter names with parameter name plus 2 asterisks" " defKey_para (x,y,n=2,*numbers,**KP):PrintX,Y,N,NUMBERS,KP#only Required ParametersKey_para () #Required, defaultKey_para (A) #required, default, keywordsKey_para (1,2,3,kw=99) #required, default, variable (array)Key_para (1,2,3,*[1,2]) #required, default, variable (array)Key_para (1,2,3,* ()) #required, default, variableKey_para (1,2,3,1,2) #required, default, keyword (dictionary)Key_para (1,2,3,**{'Test':'af','PLD':'Afe'}) #required, default, variable, keywordKey_para (1,2,3,*), kw=99) #all function arguments can be called with Func (*args,**kw).
Recursive functions:
#-*-coding:utf-8-*- " "' recursive function" " deffact (n):ifN==1: return1returnFact (n-1) *NPrintFact (10) PrintFact (100) #tail recursive solution stack Overflow#Stack Overflow#Print fact (+)#Tail recursiondeffact (n):returnFact_iter (, N)defFact_iter (N,count,max):ifCount >Max:returnNreturnFact_iter (n*count,count+1, Max)" ""But Python does not optimize the tail recursion, so the upper end recursion will still overflow stack, (that is also said a hair ah), but someone abroad has written a decorator, can solve the problem have time to study" "
Prevent overflow:
#!/usr/bin/env python2.4#This program shows off a python decorator (#which implements tail call optimization. It#does this by throwing a exception if it is#it ' s own grandparent, and catching such#exceptions to recall the stack. ImportSYSclasstailrecurseexception:def __init__(self, args, Kwargs): Self.args=args Self.kwargs=Kwargsdeftail_call_optimized (g):"""This function decorates a function with tail call optimization. It does this by throwing a exception if it is it's own grandparent, and catching such exceptions to fake the tail cal L optimization. This function fails if the decorated function recurses in a non-tail context. """ defFunc (*args, * *Kwargs): F=Sys._getframe ()ifF.f_back andf.f_back.f_back \ andF.f_back.f_back.f_code = =F.f_code:Raisetailrecurseexception (args, Kwargs)Else: while1: Try: returnG (*args, * *Kwargs)excepttailrecurseexception, E:args=E.args Kwargs=E.kwargs func.__doc__= G.__doc__ returnfunc @tail_call_optimizeddefFactorial (n, acc=1): "Calculate a factorial" ifn = =0:returnACCreturnFactorial (n-1, nACC)PrintFactorial (10000) #prints a big, big number,#But doesn ' t hits the recursion limit. @tail_call_optimizeddefFIB (i, current = 0, next = 1): ifi = =0:return CurrentElse: returnFIB (I-1, Next, current +next)PrintFIB (10000) #also prints a big number,#But doesn ' t hits the recursion limit.
Beginner Python (ix)--function