Python function Basics: Nested functions, scopes, anonymous functions, recursive functions

Source: Internet
Author: User

Nested functions:

1. function can be defined inside function

2. function is only executed after it is called

Look at the following code:

Age = +def  func1 ():    =    print(age    )def  Func2 ():        =    #  If the age is not assigned, it will first look in its parent (FUNC1), and if the parent does not, it will look for its grandfather (global age).  # One layer at a level from inside Out        Print (age)    Func2 () func1 ()#  output:#28 

Note: Variables inside the function are called local variables, but there are also hierarchical relationships between local variables

#Scenario 1:Age = 18deffunc1 ():defFunc2 ():Print(age)= 22#age=22 is still the variable inside the func1.Func2 ()#when the program runs from top to bottom, the age has been assigned a value within the function.func1 ()#Output Result:# A#Scenario 2:Age = 18deffunc1 ():defFunc2 ():Print(age) Func2 ()#The program from top to bottom to run to this step, because there is no age,func2 in the FUNC2 will be looked up, found func1 in the age=22, but because the variables need to be defined after use (fixed in front of use), so the program will error. For example Scenario 3Age = 22#Age =22 is still a variable inside the function func1func1 ()#The output will result in an error. #Scenario 3:Age = 18deffunc1 ():defFunc2 ():Print(Age2) func2 () Age2= 22func1 ()#The output will result in an error. #Scenario 4:Age = 18deffunc1 ():GlobalAge#when the program performs this step, age is declared as a global variable and is assigned a value of    defFunc2 ():Print(age)#When you do this, age calls the global variable directlyFunc2 () age= 22#when the program executes to this step, the global variable of age is then assigned a value offunc1 ()Print(age)#Output Result:# -# A#Scenario 5: Age= 18deffunc1 ():GlobalAge#In This step, age is declared as a global variable, and the value at this time isAge = 22#At this stage, age is re-assigned to    defFunc2 ():Print(age) Func2 () func1 ( )#Output Result:# A#Scenario 6:Age = 18deffunc1 ():GlobalAge#does this step be age or    defFunc2 ():Print(age)#At this stage, the age is 22.Age = 22#age, the global variable, was changed to FUNC2 before the call was made.Func2 () func1 ( )#Output Result:# A

Note: These cases are used for analysis and are seldom used in actual production.

Scope:

In Python, a function is a scope, and a local variable is actually placed in its scope.

Age = 18deffunc1 (): Age= 22defFunc2 ():Print(age)returnFunc2#Func2 without parentheses, return this function nameVal=func1 ()Print(Val)#the name of the function is printedVal ()#Val is Func2, and this will be done#Output Result:#<function Func1.<locals>.func2 at 0x0000009f6aeab9d8>##虽然是在外部执行, but is still called through its domain-defined relationship, so it is not.

After the code definition is complete, the scope is already generated. Later calls are looked up through their defined domain relationships (regardless of where the function name is called, as long as it is executed, it will return to the place where it was defined to look up.) )。

Anonymous functions:

Common functions:

Def calc (x, y):

Return X*y

anonymous function: Lambda x,y:x*y #声明一个匿名函数 (turns multiline statements into one line)

Call:

Func = Lambda x,y:x*y

Func (3,8)

The most complex of anonymous functions can only be ternary operations.

Anonymous functions are often used in conjunction with other methods, primarily to save code, such as:

#Requirement: Make the number within range (10) Multiply yourselfData= List (Range (10))Print(List (Map (Lambdax:x*x,data )))#Output Result:#[0, 1, 4, 9, +,-# Map Usage: Map (func, *iterables)--map objecT#is to iterables each of the values in the previous function. #The role of list (map) is to make the result of the map look like a list#iterables are: list,str,tuple,dict,file,xrange, etc.

Higher order functions:

Variables can point to functions, function parameters can receive variables, one function can receive another function as a parameter , this function is called the higher order function.

In addition, one function return another function, which is also a higher-order function, such as:

def func (x, y    ): return  = func (3,-10)# Func is also a high- order function #  ABS is a function of absolute value, usage: ABS (number)#  When a function returns multiple values, it is returned in the form of a meta-ancestor.

Summarize:

A higher-order function is required only if one of the following conditions is true:

1. Receive one or more functions as input

2. Return returns another function

Recursive functions:

If a function calls itself within itself, such a function is a recursive function. such as: Let 10 divided by 2, until 0.

A=Tendef Calc (n): N=int(n/2) print (n)ifn >0: Calc (n) #在函数内部调用它自己 will produce a cyclic calc (a) # Output: #5# 2# 1# 0# # and, the program at the end of the exit, is from the inward, a layer of gradually end. Test: A=Tendef Calc (n): N=int(n/2) print (n)ifn >0: #这一步的代码运行分析:the 1th time the N of print is 5, because 5>0,n directly into Calc (n), because Calc (n) calls itself, it does not go the following print (' Program exit test: ', N) this step, but return to the top of the N=int (N/2) These steps. N is 2 andThe  same is true when you are 1. Calc (n) print ('Program exit test:', n) # Print results analysis:the value of the last round of loop n is 0, at which point the n==0 no longer does Calc (n), but instead runs the following print (' Program exit test: ', n '), at which point the innermost loop ends; However, when the previous step n==1, The program is directly into the IF statement for Calc (n), and does not carry out the following print statements, so when the innermost n==0 this layer of program is finished, N==1 also have to go through the print statement. Similarly, n== 2 and 5 o'clock also go through this print statement in turn. 

Calc (a) # Output: #5# 2# 1# 0# Program Exit test:0# Program Exit test:1# Program Exit test:2# Program Exit test:5

Recursive function return value:

The return value outside of the recursive function is returned from the outermost function return, want to get the return value of the recursive function, need to have a return value in each invocation of the recursive function, only so that the inner return value can be returned to the outermost layer of return. It is written in the following ways:

If conditions are established:

Return Call Yourself

Else

Return the innermost value

For example, the following two examples:

Example 1:100 divided by 23 times, the function outside to get the return value. A= 100deffunc (n,count):ifCount < 3:        returnFunc (n/2,count+1)    Else:        returnNresult=func (a,0)Print(Result)#Output Result:#12.5Example 2: Find the factorial of 3, the function outside to get the return value. deff (n):ifn > 1:        returnN*f (n-1)    Else:        returnNPrint(F (3))#Output Result:#6

The following flowchart shows how their return values are obtained:

1. Factorial of 3:

2.100 divided by 23 times:

Python function Basics: Nested functions, scopes, anonymous functions, recursive functions

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.