Ropes Python Chapter III __ Functional programming, recursion, built-in functions

Source: Internet
Author: User
Tags vars
One, function-type programming

Create a function

A function is composed of the keyword Def, with the function name and the parentheses colon, and the arguments in parentheses, when you want to execute the function, just write the function name and parentheses

Format: def functions (parameter) create a function below

#!/usr/bin/env python#-*-coding:utf-8-*-#创建函数def print_str ():    print ("Hello World") #调用函数print_str ()


First function

Scope of the variable

Let's take a look at an example, in the following code we first put the variable a= "haha" and then put the a= "Heihei" in the function and finally execute the function, and output the result of the variable a

We find out why a is not equal to "Heihei", but the "haha" phenomenon we previously assigned.

#!/usr/bin/env python#-*-coding:utf-8-*-a = "haha" #创建函数def print_str ():    a = "Heihei"    print ("Hello World") # Call function Print_str () print ("I am variable A:", a)


Scope example of a variable

Global variables and local variables

It is clear that the scope of the variable is the scope in which the variable takes effect, and if the range is out of use

Global variables: Usually the global variable survives at the end of the script run, and all functions can access it

Local variables: called only within the function of the local variable, and other functions cannot be called unless the local variable is declared as a global variable, and the local variable

When the function execution is complete, it does not exist.

#!/usr/bin/env python#-*-coding:utf-8-*-a = "haha" #创建函数def print_str ():    a = "Heihei"    print ("I am a local variable A:", a) # Call function Print_str () print ("I am the global variable A:", a)


Global variables and local variables

Global

Global is the ability to turn local variables into global variables, if the declared local variable name is the same as the global variable name, then the local variable will overwrite the global variable, cut

Declaring a variable with global requires declaring it before the variable otherwise python will tell you that you need to declare it in front of a

Error hint: Syntaxwarning:name ' A ' is assigned to before global Declaration global A

#!/usr/bin/env python#-*-coding:utf-8-*-a = "haha" #创建函数def print_str ():    global a    = "Heihei"    print (" I am the local variable A: ", a) #调用函数print_str () print (" I am the global variable A: ", a)


Gloable

Second, to participate in the return value

Pass the reference

The function is simple and easy to understand, but the parameters change more, in the function parentheses are parameters, parameters can receive strings, numbers, can also receive dictionaries and lists

And in the call, we can also specify which parameter to assign what value

#!/usr/bin/env python#-*-coding:utf-8-*-#创建函数def print_str (name,age,aender):    print ("'    name:%s    age:% s    aender:%s    "% (name,age,aender)) #用户输入in_name = input (" Please enter your name: ") In_age = input (" Please enter your Age: ") In_aender = Input ("Please enter your Gender:") #固定位置传参print_str (in_name,in_age,in_aender) print ("----------------------------------") # Non-stationary position parameter print_str (in_name,aender=in_aender,age=in_age)


Pass the reference

What do we need to do when we want to pass in a list or dictionary?

#!/usr/bin/env python#-*-coding:utf-8-*-def print_str (lists):    if Type (lists) = = List:        print ("'        name:%s        age:%s        aender:%s "        % (lists[0],lists[1],lists[2])    else:        print (" '        name:%s        age:%s        aender:% S        '% (lists["name"],lists["Age"],lists["Aenber"])) #传入列表userlist = ["Ben", "Ten", "Man"]print_str (userlist) Print ("----------------------------------") #传入字典userdict = {"Name": "Ben", "Age": "022", "Aender": "Mans"}print_str ( userlist)


Incoming dictionary or List

Default parameters

In the function can also set the default parameters, the default parameter means that the parameter you can pass the value can also not pass the value, when the value is not passed this parameter is equal to the default value

#!/usr/bin/env python#-*-coding:utf-8-*-def print_str (lists,country= "China"):    if Type (lists) = = List:        print ('''        name:%s        age:%s        aender:%s        country:%s        "% (lists[0],lists[1],lists[2],country))    else:        Print ('        name:%s        age:%s        aender:%s        country:%s        '% (lists["Name"],lists["Age"],lists[" Aenber "],country)" #传入列表userlist = ["Ben", "Ten", "Man"]print_str (userlist) print ("---------------------------------- ") #传入字典userdict = {" Name ":" Ben "," Age ":" 022 "," Aender ":" Man "}print_str (userlist," America ")


Default parameters

Non-fixed parameters

The meaning of a non-fixed parameter is that you can receive any value that you use when your function is unsure of how many values the user wants to pass, but we can not pass arguments when we call a function that has only non-fixed arguments.

Non-fixed parameters of a * and two *,*args will be passed into the parameters of the progenitor, **kwargs the passed parameters into a dictionary, of course *ages can be other names, but it is best to use *args in the specification, and **kwargs

#!/usr/bin/env python#-*-coding:utf-8-*-def print_str (*args,**kwargs):    print ("I am *", args)    print ("I am * *", Kwargs) #传入列表userlist = ["Ben", "Ten", "Man"]print_str (userlist, "America") print ("----------------------------------" ) #传入字典print_str (A = "1", B = "2")


Non-stationary pass parameters

Since the formal parameter can take * and * *, then the argument can also take * and * *, then * is used with the list, * * is a dictionary!

#!/usr/bin/env python#-*-coding:utf-8-*-def print_str (*args,**kwargs):    print ("I am *", args)    print ("I am * *", Kwargs) #传入列表userlist = ["Ben", "Ten", "Man"]print_str (*userlist) print ("----------------delimiter----------------") # Incoming dictionary userdict = {"Name": "Ben", "Age": "022", "Gender": "Mans"}print_str (**userdict)


The solution parameter

The argument band * will break down the list into "Ben", "a", "man" a separate element into the function, and * * will decompose the dictionary into Name= "Ben", age= "022", gender= "man"

This key-value pair passes in the function.

  

form participates in the actual parameter

Formal parameters:

A variable allocates a memory unit only when it is called, releasing the allocated memory unit immediately at the end of the call. Therefore, the formal parameter is only valid inside the function. Function call ends return to main call

function, you can no longer use the shape parametric

Actual parameters:

Can be constants, variables, expressions, functions, and so on, regardless of the amount of the arguments, they must have a definite value when making a function call to pass these values to the parameter. So

You should use the assignment, input and other methods to get the parameters to determine the value

  

Note! When the normal parameters and the default parameters and non-fixed parameters are used together, to follow a sequence, the normal parameters before the default parameters, the default parameters in front of the non-fixed parameters

  

return value

When the function is normally used, the function can return the result of the function's internal processing to the function caller, and the return value can return the sequence, etc.

The return function will stop executing when the function executes and return the result

#!/usr/bin/env python#-*-coding:utf-8-*-#创建函数def print_str (age):    the If int (age) <=:        return "You're%s!"% ( Age)    Else:        return "You are all%s!" the old man. In_age = input ("Please enter your Ages:") Word = Print_str (in_age) print (word)

Return  

Nested functions

Functions can also be written inside the function, so that the outer function is nested inside the function, which is called a nested function, because the scope of the relational nesting function can only be called internally

Return Unction_2 (stra) + "I am the second layer \ \" is the first c = unction_2 (stra) and then return c+ "I am the second floor \ n"

def unction (stra):    def unction_2 (stra_2):        return stra_2+ "I'm the third layer \"    return Unction_2 (stra) + "I'm the second floor \" R_ str = unction ("") Print (r_str+ "I am the first layer")


nested Functions

Third, recursion

The function-related knowledge has been described earlier, in which functions can call other functions, and functions can call themselves, and with this feature we can accomplish some specific

Operation, the form of this function call itself is recursive

def recursion ():
return recursion ()

In recursion, you can't always call itself like the two lines above, so that a program crashes because it never goes out in the same way as the while loop, so recursion needs to go in.

Judge to export it

Example: factorial

What is factorial, factorial is to give a natural number n, and then calculate the factorial of n then n = 1x2x3x4 .... N, this is factorial, we can take it to the point of view,

n = n x (n-1) x (n-2) x (n-3) ... 1 The value that has been multiplied into parentheses equals 1, now that we know what factorial is, let's write a program to implement it

def factorial (n): for     I in range (1,n):         n *= i     return n c = factorial (4) print (c)

Factorial non-recursive version

Anatomy: The above example first put n=4 in, and then through for the I in range (1,4) I was equal to three to three, and then n*=i, we can see that the for loop is a loop 3 times

The first time (n = n*i) n = 4*1, at which point N is still equal to 4

The second time (n = 4*i) n = 4*2 at this time n = 8

The third time (n = 8*i) n = 8*3 at this time n equals 24

At this point the For loop is 3 times so it ends and returns the result of n by return, so the final result calculates that the factorial of 4 equals 24.

Recursive version

Here's a look at the factorial of the recursive version

def factorial (n):    if n = = 1:        return 1    else:        return n * factorial (n-1) c = factorial (4) print (c)

Factorial recursive version

Analysis:

First C = factorial (4) began to execute the function, and then the first judgment n = = 1, obviously the first layer n is not equal to 1, and then hit return n * factorial (n-1), encountered return is originally to return, but factorial (n-1)

There is a function called factiorial, so it enters the second level.

The second layer because the last layer passed in the parameter is n-1, so the second layer of n is equal to 3, and then judge, this layer of n is not equal to 1, and then into the third layer

The third layer, n equals 3, then determines that the N of this layer is not equal to 1, and then enters the fourth floor.

  

To the fourth level when the n is equal to 1, so triggered by return 1 no longer calls the function, so began to return

Return to the third layer return n * factorial (n-1), at this time factorial (n-1) is equal to the fourth return up 1, so the third layer returns is equal to return n * 1 (return 2 * 1), and the third layer n is equal to 2

Return second layer factorial (n-1) is equal to the third layer return up 2, and the second layer n is equal to 3, return 3 * 2

Return to the first layer factorial (n-1) is equal to the second layer return up 6, and the first layer n is equal to 4, return 4 * 6

So far the recursion is done and C equals 4 * 6 c=24

  

  

Iv. Anonymous functions

The anonymous function is also called a lambda function, and the function does not have a specific name. Syntax: function name= lambda args (multiple arguments separated by commas): expression (the result of an expression is the return value)

Let's take a look at one of the simplest examples:

#普通函数def func (ARG1,ARG2):    return arg1-arg2#lambda function func_2 = lambda arg1,arg2:arg1-arg2# parameter execution print (func (5,4)) Print (func_2 (5,4))

anonymous functions

There is no difference between this anonymous function and the normal function, in fact, the anonymous function is like the ternary operation, and can use the lambda function has several advantages

1. In some functions that are not called anywhere else, we can use anonymous functions, and this simplifies the code and looks neater.

2. The lambda function will be used with some built-in functions (which will be covered below)

Five, closed package

In the above example, knowing that a function can call the function itself, which is called recursion, you can also return the function as a parameter, which is called a closure

The biggest benefit of closures is the use of instant-on, closures are useful for installing calculations, hiding states, and switching freely between function objects and scopes!

#!/usr/bin/env python#-*-coding:utf-8-*-def func (rate):    count = [0]    def add_func (ARG):        count[0] +=1        Print ("%s call"%count[0])        arg = arg-arg*rate        return arg    return add_funcclosure = func (0.03) print (Closure ( ) Print (Closure (1100)) Print (Closure (1200))

Closures Example

In the example, a function that returns the balance minus the handling fee is performed, the Func function is executed first, the interest rate is encapsulated, and then the Func function returns the function inside it.

You know, when the function is not in parentheses, it is not executed! , so at this point closoure is the memory address of the Add_func function, and when you want to use this function, directly add the closoure parentheses

and pass in the value to execute. And you can see that it is executed in the global scope and can be switched to the local scope at any time.

Six, higher order functions

function can be used as the return value, you can call itself, the higher-order function is the function of the parameters of the other function as a parameter, this function is called higher-order function.

def func_1 (num):    return num+1def func_2 (num):    return num-1def Func_main (num,func):    #  can be shortened to return Func (num)    results = func (num)    return resultsresults = Func_main (10,func_1) print (results) print (Func_main (10, func_2))

Higher order functions

Writing higher-order functions allows the parameters of a function to receive other functions.

  

Seven, built-in functions

Built-in functions are some of the methods built into Python

  

The built-in function uses the method example, the detailed introduction please refer

#!/usr/bin/env python#-*-coding:utf-8-*-#返回数字的绝对值. Parameters can be integers or floating-point numbers. If the argument is a complex number, its size is returned. Print (ABS ( -1.11)) #传入一个可被循环的元素, if there is a false in this element is false # 0 Null value false is False print (all ([])) #与all相反, only one is true, then true; print (Any ( [0,2,false])) The #这个函数跟repr () function returns a printable representation of an object string. When a non-ASCII code is encountered, the # will output \x,\u or \u characters. The repr () in Python version 2 is the equivalent function. Print (ASCII ("Dsads"), ASCII ($), ASCII (' b\23 ')) #将十进制转换为二进制; print (bin) #返回布尔值, which is either true or false, if the argument is False or omitted, then returns false; Otherwise, returns True. Print (bool (1)) #根据传入的参数创建一个新的字节数组 # If the incoming string must give the encoded print (ByteArray (' Hello ', ' utf-8 ')) #当source参数是一个可迭代对象, Then the elements in this object must conform to more than 0 less than 256print (ByteArray ([256,1,2])) #返回一个的 "bytes" object, return bytes type bytes (' Chinese ', ' utf-8 ') #检查对象是否可以被调用def Func (): Passprint (Callable (func)) #返回整数所对应的Unicode字符, Chr (97) returns the string ' a ', and Chr (8364) returns the string ' € '. Print (Chr (126)) #是用来指定一个类的方法为类方法, a class method can be called directly without instantiating class A: @classmethod def B (Cls,arg1,): Print (ARG1) a.b (1) A (). B (1) #将源编译为代码或者AST对象. The code object can be evaluated by EXEC statement execution or eval (). #源可以是正常字符串, a byte string or an AST object. expr = "5+5-1" obj = compile (expr, "", "eval") Print (eval (obj)) #返回值为real + imag * J Complex number or conversionA string or number is a plural. If the first argument is a string, you do not need to specify a second argument. Print (Complex (1, 2)) print (complex (1)) Print (Complex ("1+2j")) # parameter is an object and a string. The string must be the name of one of the object properties. Class A:def A1 (self): print ("A1") def A2 (self): print ("a2") obj = Aprint (dir (obj)) delattr (obj, "A1") PR The Int (dir (obj)) #dir returns the method in the object strs= "AAA" Print (dir (STRs)) #返回两个数值的商和余数print (Divmod (7,3)) #用于遍历序列中的元素以及它们的下标print ( Enumerate ([i,j])) #返回的是可迭代的对象for in Enumerate ((' A ', ' B ', ' C ')): print (I,J) #将字符串str当成有效的表达式来求值并返回计算结果. Print (eval ("1+2+3")) Print (eval ("False or True") #字符串str当成动态语句块执行并返回结果exec (' a=1+2+3 ') print (a) #使用指定方法 (method, function), Filter elements of an iterative object def add (ARG): return arg > 3for i in Filter (add,[1,2,3,4,5]): Print (i) #浮点型print (float) #格式化显示 more ways to see Examiner Side Description Print (' {:,. 2f} '. Format (111111)) #根据传入的参数创建一个新的不可变集合a = Frozenset ([1,2,3,4,5]) print (a) #获取对象的属性值class a (): Def __ Init__ (self,): Self.name = "123" B = A () print (GetAttr (b, ' name ')) #返回当前作用域内的全局变量和其值组成的字典print (Globals ()) #检查对象是否含有属性cla SS A (): Def __init__ (self,): Self.name = "123" B = A () print(Hasattr (b, ' name ')) #哈希值计算 # is unique in the current environment print (hash (' Hello ')) #help帮助def Funcs (args): "" Function description:p Aram A Rgs:args = List:return: "" "Passprint (Help (Funcs)) #转换16进制print (Hex ()) #显示对象的标识符print (ID (" 123 ")) #input标准输入s = i Nput ("User name:") print (s) #int返回整数print (int (1.2)) Print (int ("2")) #判断对象是否是类或者类型元组中任意类元素的实例print (Isinstance ("1", int)) Print (Isinstance (1.1, (Int,float))) #判断类是否是另外一个类或者类型元组中任意类元素的子类print (dir (str)) print (Issubclass (ByteArray, STR) print (Issubclass (bool,int)) #根据传入的参数创建一个新的可迭代对象a = iter (' 12345 ') print (Next (a)) #返回对象的长度lena = [ 1,2,3,4] #转换列表print (List ("ABCD")) #返回当前作用域内的局部变量和其值组成的字典def A (): Print (Locals ()) s = 1 print (locals ()) a () #使用指定方法去作用 The elements of each iteration object that are passed in, generating a new iterator object def add (x): Return x+100lists = [1,2,3,4]for i in Map (add,lists): Print (i) #max: Returns the maximum value of print (max (a)) Print (max ([1,2,3,4])) #在进行切片并赋值数据时, do not need to copy the original list data, you can directly map the original data memory; s = Memoryview (b ' ABCD ') print (s[1]) #返回最小值print (min ( ) Print (min ([2,3])) #返回可迭代对象中的下一个元素值a = iter (' 1234 ') print (NEXT (a)) #创建一个新的object对象 (new Class) class B (object): pass# converted to 8 binary string print (Oct) #open文件操作file = open (' Test.txt ', encoding= " Utf-8 ") #ord: Returns the integer that corresponds to the Unicode character print (Ord (" A ")) #幂运算print (POW (2,3)) #标准输出print () #property: Use specific methods in the adorner # class that identifies the attribute please Baidu, Or wait for subsequent updates Property#range: Creates a new Range object based on the parameters passed in range (1,10) "" "Repr () function The resulting string is usually used to regain the object. The input to Repr () is more friendly to Python. Typically, the Obj==eval (repr (obj)) equation is established. "" "obj= ' Python ' Print (eval (repr (obj))) #翻转序列a = reversed ([1,2,3,4,5]) Print (list (a)) #round: Rounds the value of the floating-point number print (round ( 1.5)) #set converted to set print ([__init__]) #setattr: Sets the property value of the object class A (): Def (self,age): Self.age = ages = A (one) PRI NT (S.age) setattr (S, ' age ', 3) print (s.age) #根据传入的参数创建一个新的切片对象c1 = Slice () C2 = Slice (2,4) C3 = Slice (0,5,2) s = [ 1,2,3,4,5,6]print (S[C1]) print (S[C2]) print (S[C3]) #排序, returns a new list by default by character ascii sort a = [4,3,2,1,7]print (sorted (a)) #        Decorator class B (object): Def __init__ (self,age): Self.age = age @staticmethod def hello (args): Print (args) B.hello ("Hello World") #字符串类型print (str (123)) #求和print (sum ([1,2,3,4])) #根据传入的参数创建一个新的子类和父类关系的代理对象class A (object): Def __init__ (self): print ("I am a Clase") class B (a): def __init__ (self): print ("I am B Class") Super (). __init__ () B = B () #元祖tuple ([1,2,3,4]) #type returns the type of the object print (t Ype ([1])) Print (Type ("1")) #返回当前作用域内的局部变量和其值组成的字典, or return the object's property List Def func (): Print (VARs ()) s = 1 print (VARs ()) func () #聚合 Returns an element of the same position in each iterator passed in, returning a new tuple type iterator List1 = [1,2,3]LIST2 = ["A", "B", "C", "D"]print (Zip (list1,list2)) for I in Zip (list1,list2 ): Print (i) #__import__: Dynamic Import Module __import__


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.