## 1、 Nested function

Multiple functions nested together is called function nesting

When the function is called , Functions need to be defined before calling , If the function is defined after it is called , Cannot be called successfully .

When defining multiple functions , Function names cannot be the same , Otherwise, the later defined function will cover the previous function , That is, the previous function fails .

# Define a function , Draw a line

def printLine():

print('-'*30) # Define a function , Call the previous function , And draw the specified number of horizontal lines according to the value entered by the user

def stringPrint(index):

i = 0

while i<index:

printLine()

i+=1 indexNum = int(input(' Please enter the number of lines in the horizontal line ：'))

stringPrint(indexNum)

Be careful ：

The initial requirement is to draw a line , When it needs to be changed to set out according to user needs n When there is a horizontal line , Don't change the original function code directly , Because the original function may also be called elsewhere , Instead, a function should be redefined to implement the new function , When the function of the original function needs to be repeated , You can call the original function directly , Instead of writing the code of the original function repeatedly .

** seek 3 The number and 、3 The average of the numbers **

# Define a function , seek 3 The number and ：

def sum3Num(a,b,c):

sum = a+b+c

return sum # Define a function , seek 3 The average of the numbers

def ava3Num(a,b,c):

sum = sum3Num(a,b,c)

ava = sum/3

return ava a = int(input(' Please enter the first number ：'))

b = int(input(' Please enter the second number ：'))

c = int(input(' Please enter the third number ：')) result = sum3Num(a,b,c)

ava = ava3Num(a,b,c)

print(' And for %d'%result)

print(' The average value is %d'%ava)

## 2、 Higher order function

Since variables can point to functions , The parameters of the function can receive variables , Then one function can take another function as an argument , This kind of function is called higher order function .

One of the simplest higher-order functions ：

1 def add(x, y, f):

2 return f(x) + f(y)

When we call add(-5, 6, abs) when , Parameters x,y and f Receive separately -5,6 and abs

add(-5, 6, abs)

11

Write higher-order functions , It means that the parameters of the function can receive other functions .

** There are two cases of higher order functions ：**

1、 Pass the memory address of one function to another as a parameter

2、 One function returns another function as a return value

** Example **

Write a function calc_prod(lst), It receives a list, Returns a function , The return function calculates the product of the parameters .

def calc_prod(lst):

def lazy_prod():

def f(x, y):

return x * y

return reduce(f, lst, 1)

return lazy_prod

f = calc_prod([1, 2, 3, 4])

print f()

In function calc_proc The internal function returns the value of the internal function , But no call to the inner function , So name variables globally f The function is not called lazy_prod()

When f() When it is called , You can choose to go through f() To call , Also known as deferred calls .

If the function calc_proc It's back inside lazy_prod() In this case, the variables will be defined globally f The internal function is called when the .

## 3、 Recursive function

Inside the function , You can call other functions . If a function calls itself internally , This function is a recursive function .

python The default recursive function can have at most 999 layer , You can also change the default value

import sys

sys.setrecursionlimit(10000)

def func(x):

print(x)

x +=1

func(x)

func(1)

Change the default limit level of recursive function to 10000, The actual execution of the test can be 8000 many times , Want to see PC Performance .

for instance , Let's calculate the factorial n! = 1 x 2 x 3 x ... x n, Use functions fact(n) Express , It can be seen that ：

fact(n) = n! = 1 x 2 x 3 x ... x (n-1) x n = (n-1)! x n = fact(n-1) x n

therefore ,fact(n) It can be expressed as n x fact(n-1), Only n=1 It needs special treatment .

If we calculate fact(5), You can see the calculation process as follows according to the function definition ：

===> fact(5)

===> 5 * fact(4)

===> 5 * (4 * fact(3))

===> 5 * (4 * (3 * fact(2)))

===> 5 * (4 * (3 * (2 * fact(1))))

===> 5 * (4 * (3 * (2 * 1)))

===> 5 * (4 * (3 * 2))

===> 5 * (4 * 6)

===> 5 * 24

===> 120

therefore ,fact(n) It's written recursively ：

def fact(num):

if num == 1:

return 1

return num*fact(num-1) result = fact(5)

print('fact=%d'%result)

perhaps

def fact(num):

if num>1:

return num*fact(num-1)

return 1

Calculation 10 The factorial of can also be used reduce

from functools import reduce

def fact(n):

return reduce(lambda x,y:x*y, range(1,n+1) )

print(fact(10)) Or direct output ：

print(reduce(lambad x,y:x*y, range(1,11)))

You can also use for Loop multiplication

def cal(n):

result = 1

for i in range(1,n+1):

result *=i

print(result)

cal(4)

Or in reverse order

def cal(n):

for i in range(n-1,0,-1):

n*=i

return n

print(cal(4))

or

def cal(n):

result = 1

for i in range(n,0,-1):

result*=i

return result

print(cal(4))

** Example ：*** Generate a Fibonacci sequence *

def fib(max):

a = 0

b = 1

n = 0

while n<max:

print(b)

a, b = b, a+b

n+=1

fib(8)

result ：

1

1

2

3

5

8

13

21

** Outputs the number of the specified subscript in the Fibonacci sequence **

def fib2(n):

if n == 1 or n == 2:

return 1

elif n > 2:

return fib2(n-2) + fib2(n-1)

print(fib2(5))

result ：5

** Example ： Put... In the list 3 Become a string ‘101’**

lis = [2, 3, "k", ["qwe", 20, ["k1", ["tt", 3, "1"]], 89], "ab", "adv"]

# Create a list loop function , If the element is still a list , Call the list loop function again , Until the element is not a list type , Then judge if the element is equal to 3 Just replace it with '101'

def change(li, old, new):

for i in range(len(li)):

if isinstance(li[i], list):

change(li[i],old,new)

if li[i] == old:

li[i] = new

change(lis, 3, '')

print(lis)

**4、 Two points search **

li = [1,2,3,5,6,8,10,12,15,16,17,18,20]

#li_1 = list(range(1,10000000))# I tried and looked up 22 I can check 1000 ten thousand , check 1 We need 25 Time , The computer is going to crash. I don't know why

def find(find_str, lst, count):

mid = len(lst) // 2

if len(lst) == 1:

if find_str == lst[0]:

count +=1

print(' Look for it. ' + str(count) + ' I found it once ')

elif mid > 0:

if lst[mid] == find_str:

count += 1

print(' Look for it. ' + str(count) + ' I found it once ')

elif lst[mid] > find_str:

find(find_str, lst[:mid], count + 1)

else:

find(find_str, lst[mid + 1:], count + 1)

else:

print(' Look for it. ' + str(count) + ' I didn't find it twice ')

find(200,li, 0)

## 5、 Function return value

Python Not only does the function return int、str、list、dict And so on , You can also return functions ！

for example , Define a function f(), Let's let it return a function g, It can be written like this ：

def f():

print 'call f()...'

def g():

print 'call g()...'

return g

Take a closer look at the function definition above , We are in function f There's another function defined inside g. Due to function g It's also an object , Function name g It's pointing to the function g The variable of , therefore , The outermost function f You can return variables g, That's the function g In itself .

Call function f, We will get f A function that returns ：

>>> x = f() # call f()

call f()...

>>> x # Variable x yes f() Return function ：

<function g at 0x1037bf320>

>>> x() #x Pointing function , So you can call

call g()... # call x() Is to perform g() Function defined code

Note the distinction between return functions and return values ：

def myabs():

return abs # Return function

def myabs2(x):

return abs(x) # Returns the result of a function call , The return value is a numeric value

The return function can delay some calculations . for example , If you define a normal summation function ：

def calc_sum(lst):

return sum(lst)

call calc_sum() Function time , Will immediately calculate and get the results ：

>>> calc_sum([1, 2, 3, 4])

10

however , If you return a function , Can “ Delay calculation ”：

def calc_sum(lst):

def lazy_sum():

return sum(lst)

return lazy_sum

# call calc_sum() It didn't work out , It's a return function :

>>> f = calc_sum([1, 2, 3, 4])

>>> f

<function lazy_sum at 0x1037bfaa0>

# When calling the returned function , Just calculated the result :

>>> f()

10

Because you can return a function , We can decide whether to call this function or not in the following code .

** Example ：**

Write a function calc_prod(lst), It receives a list, Returns a function , The return function calculates the product of the parameters .

from functools import reduce

def calc_prod(lst):

def lazy_prod():

def f(x, y):

return x * y

return reduce(f, lst, 1)

return lazy_prod

a = calc_prod([1, 2, 3, 4])

print(a())

result ：24

## 6、 Closure

Functions defined inside functions are the same as functions defined outside , It's just that they can't be accessed from outside ：

def g():

print 'g()...' def f():

print 'f()...'

return g

take g Move the definition of into the function f Inside , Prevent other code calls g：

def f():

print 'f()...'

def g():

print 'g()...'

return g

however , For example, as defined below calc_sum function ：

def calc_sum(lst):

def lazy_sum():

return sum(lst)

return lazy_sum

Be careful : Found it impossible to lazy_sum Move to calc_sum The outside of the , Because it quotes calc_sum Parameters of lst.

Inner functions like this refer to variables of outer functions （ Parameters are also variables , And it's a non global variable ）, Then return the inner function layer by layer , It's called closure （Closure）.

The characteristic of closures is that the returned function also refers to the local variables of the outer function , therefore , To use closures correctly , It is necessary to ensure that the referenced local variables cannot change after the function returns . Examples are as follows ：

# Hope to return once 3 A function , Separate calculation 1x1,2x2,3x3:

def count():

fs = []

for i in range(1, 4):

def f():

return i*i

fs.append(f)

return fs

f1, f2, f3 = count()

print(f1(),f2(),f3())

You might think that calling f1(),f2() and f3() The result should be 1,4,9, But the actual results are all 9（ Can verify ）.

The reason is when count() Function returned 3 When functions , this 3 Variables referenced by two functions i The value of has become 3. because f1、f2、f3 Not called , therefore , At this point they did not calculate i*i, When f1 When called ：

>>> f1()

9 # because f1 Now it's time to calculate i*i, But now i The value of has changed to 3

therefore , Return functions do not reference any loop variables , Or variables that will change in the future .

Return closures cannot refer to loop variables , Please rewrite count() function , Let it return correctly to be able to calculate 1x1、2x2、3x3 Function of .

def f(j):

def g():

return j*j

return g

It can correctly return a closure g,g Variables quoted j It's not a loop variable , So it's going to work .

stay count Inside the loop of a function , If with the help of f function , You can avoid referring to loop variables i.

def count():

fs = []

for i in range(1, 4):

def f(j):

def g():

return j*j

return g

r = f(i)

fs.append(r)

return fs

f1, f2, f3 = count()

print(f1(), f2(), f3())

** or **

def count():

fs = []

for i in range(1, 4):

def f(j):

return j*j

fs.append(f(i))

return fs f1,f2,f3=count()

print(f1,f2,f3)

The result is 1,4,9

** Example 2**

li = []

for i in range(10):

def func():

return i

li.append(func) for j in li:

print(j())

The result is all 9, Because in the loop, only the function name or memory address is added to the list , Instead of calling the function , because i The value of is not added to the list # And when the function in the loop list , It's called one by one i Value , At this time i by 9

print(li)

You can see that the list is just the memory address of the function [<function func at 0x02781A50>, <function func at 0x027818A0>, <function func at 0x02781A98>, <function func at 0x02781B28>,

<function func at 0x02781B70>, <function func at 0x02781BB8>, <function func at 0x02781C00>, <function func at 0x02781C48>,

<function func at 0x02781C90>, <function func at 0x02781CD8>]

li = []

for i in range(10):

def func():

return i

li.append(func())

print(li)

result ： [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

This time the function is called in the loop func(), So the result is that i The value loop of is added to the list

l1 = [lambda x:x+i for i in range(10)]

for j in l1:

print(j(1))

# The result is all 10, Because the list is 10 A function memory address , Calling j() The final i=9 Passing in functions

print(l1)

#[<function <listcomp>.<lambda> at 0x02151A98>, <function <listcomp>.<lambda> at 0x02151AE0>, <function <listcomp>.<lambda> at 0x02151A50>,

<function <listcomp>.<lambda> at 0x021518A0>, <function <listcomp>.<lambda> at 0x02151BB8>, <function <listcomp>.<lambda> at 0x02151C00>,

<function <listcomp>.<lambda> at 0x02151C48>, <function <listcomp>.<lambda> at 0x02151C90>, <function <listcomp>.<lambda> at 0x02151CD8>,

<function <listcomp>.<lambda> at 0x02151D20>]

l2 = (lambda x:x+i for i in range(10))

for j in l2:

print(j(1))

# The result is 1-10, Because with () A generator expression is generated , Return value only when called

print(l2)

#<generator object <genexpr> at 0x0215EB70>

** Example 3**

Python Encounter closures , Space doesn't disappear with the end of function execution , Saving closure data does not destroy it

def wrapper(x):

n = 1

def inner():

nonlocal n

n += x

print(n)

return inner ret = wrapper(5)

ret()

ret()

ret()

ret()

6

11

16

21

** The method of judging closure function __closure__**

# Output __closure__ Yes cell Elements ： It's a closure function

def func():

name = 'eva'

def inner():

print(name)

print(inner.__closure__)

return inner f = func()

f() # Output __closure__ by None ： It's not a closure function

name = 'egon'

def func2():

def inner():

print(name)

print(inner.__closure__)

return inner f2 = func2()

f2()

from urllib.request import urlopen def index():

url = "http://www.xiaohua100.cn/index.html"

def get():

return urlopen(url).read()

return get xiaohua = index()

content = xiaohua()

print(content)

## day15- More related articles on function advancement

- 10.Python A glimpse of the door ( Function advanced )
Python( Function advanced ) One . Arguments to functions ( Follow up ) Parameter angle ( There are four kinds , The latter two ) Dynamic parameters ( Universal parameters )* # When defining a function ,* All location parameters are aggregated into a tuple def func(*args): # * ...

- In depth understanding of javascript The first in the series of advanced functions —— Higher order function
In front of the word The basic usage of functions is introduced in the previous function series . Start with this article , Will introduce javascript Advanced series of functions , In this paper, we will introduce higher-order functions in detail Definition Higher order function (higher-order function) A function that operates a function ...

- 【python 3】 function Advanced
Function advanced 1. Function namespace and scope There are three types of namespaces : Global namespace Local namespace Built in namespace * The built-in namespace holds python The interpreter gives us the name :input , print , str ...

- day11.1 Function advanced List collection Function variables in the dictionary , Function as a formal parameter
Function advanced 1. Function as variable a=123 name="gao" nums=[1,2,3] data=nums# Point to the same memory address # Look at the memory address def func(): prin ...

- python Basics ( Initial recognition function & Function advanced )
The basic part of function . What is a function ? Functions are organized , Reusable , To achieve oneness , Or code snippets associated with functions . Function can improve the modularity of application , And code reuse . 2. Defined function Definition :def Key words start with , Space followed by function name ...

- day 10 - 1 Function advanced
Function advanced Namespace and scope Namespace Namespace There are three built-in namespace —— python Interpreter Namely python The names that the interpreter can use as soon as it starts are stored in the built-in namespace The built-in name is loaded into memory when the interpreter is started ...

- python The foundation Initial recognition function & Function advanced
The basic part of function 1. What is a function ? Functions are organized , Reusable , To achieve oneness , Or code snippets associated with functions . Function can improve the modularity of application , And code reuse . 2. Defined function Definition :def Key words start with , Space followed by function name ...

- python Function advanced （ Function parameter 、 Return value 、 Recursive function ）
Function advanced The goal is Function parameters and return values The return value of the function Advanced The parameters of the function Advanced Recursive function 01. Function parameters and return values Functions are based on There are no parameters as well as Is there a return value , Sure Combine with each other , Altogether 4 Kind of Combination ...

- python Dafa is good —— recursive 、 Built in functions 、 Function advanced
1. recursive ( Do it yourself ) def fun(n): n=n/2 print(n) if(n>2) fun(n) # Function call fun(10) The result is 5 2 1 0 Recursive execution : Recursion to the innermost layer ...

- Baptize the soul , Practice python（25）-- Custom function （6）— From the advanced topic of anonymous function “ Functional programming ”
Anonymous function advanced The previous chapter talked about anonymous functions , Anonymous functions can also be used in combination with other built-in functions 1.map map(): mapper , mapping list(map(lambda x:x*2,range(10))) # hold range produce ...

## Random recommendation

- JAVA Internal class related
Recently, I'm looking at the implementation of singleton pattern , See there's a use JAVA Static inner class features , I really don't know about inner classes , So I got to know , Code post . /** * The inner class is divided into : Member inner class . Local inner classes . Anonymous inner class and static inner class . */ ...

- Exception in thread "http-apr-8080-exec-2"
Set up catalina.bat.catalina.sh It doesn't work MyEclipse Select menu Windows---preferences---MyEclipse---Servers---Tomcat-- ...

- ReactJS introduction
React Introduce React yes facebook Development is based on component driven development (CDD ) Of UI Class library , Relative to the class library of bidirectional binding , Such as AngularJS, It uses one-way data stream binding . By using virtual DOM The concept of , Yes, he's in performance and handling ...

- getElementById What's back ？ Collusion HTML DOM
1. getElementById() What's back ? This function is most commonly used , But did you dig into it , What exactly does this function return ? Let's have a look at . var mydivEle = document.get ...

- SQL GROUP BY sentence
Aggregate function ( such as SUM) Often need to add GROUP BY sentence . GROUP BY sentence GROUP BY Statement is used in conjunction with the aggregate function , Group result sets according to one or more columns . SQL GROUP BY grammar ...

- MD5 encryption js file
var hexcase = 0; var b64pad = ""; var chrsz = 8; function hex_md5(s){ return binl2hex(core ...

- was unable to start within 45 seconds. If the server requires more time, try increasing the timeout
stay eclipse start-up tomcat Encountered a timeout when 45 Second question : Server Tomcat v7.0 Server at localhost was unable to startwithin 45 sec ...

- Asp.net core Learning notes ( ef core )
to update : 2018-11-26 Here's about foreignKey cascade action By default, if we use data annotation required + foreginkey ...

- infra Dashboard effect
private void Gauge2() { // Infragistics.WebUI.UltraWebGauge.UltraGauge ultraGauge2 = //new Infragist ...

- [EntityFramework] Yes DateTime Type used SQL Server time or field default
DateTime Type in the SQL If the default value is set on the server , stay EntityFramework You want to use this default value when adding new rows , It can't be applied to the newly added entity DateTime Field assignment . But if new entities are added ...