Python study notes the third day

Source: Internet
Author: User
Tags abs

    • Parameters of the function
    • Local variables and global variables
    • Recursive functions and anonymous functions
    • Higher order functions
    • Functional Programming Understanding
I. Various parameters of the function

Key parameters and positional parameters: just remember that key parameters must be placed after the position parameter.

#参数问题def Test (z/y): Print (    x)    print (    z=1,x=2,y=3) #2, 3, 1, the order of key parameters is unaffected by test (all-in-A-Z) # The position parameter order is the incoming order #test (1,y=2,4) #error, the key parameter must be placed behind the position parameter Test (1,z=2,y=2)

Non-fixed parameter (variable parameter?) ): *args,**kwargs

#可变参数def test1 (*args): #形参的数量不固定    print (args) test1 (1,2,3,4,5,) #实参放入元组中 # bind position parameter Def test2 (X,*args):    print (x)    print (args) test2 (1,2,3,4,5,6,7) #接受字典的可变参数---keyword parameter def test3 (**kwargs):    print (Kwargs) test3 (name= ' Sun ', Age= ' 8 ', sex= ' M ', tall= "168") Test3 (name= ' Sun ') #组合使用def test4 (Name,**kwargs):    print (name)    print (Kwargs) Test4 (' Sun ') test4 (' Sun ', age=10) test4 (' Sun ', age=10,sex= "M") def TEST5 (Name,age=10,**kwargs):    print (name)    Print (age)    print (Kwargs) test5 (' Sun ', 24,hobby= ' sleep ') test5 (' Sun ', sex= ' m ', age=3) #age =3 position can be placed behind Def TEST6 ( Name,age=18,*args,**kwargs): print (name) print (age) Print (    args)    print (Kwargs) test6 (' Sun ', 24,1,2,3,sex= ' m ', hobby= ' sleep ') #注意以下 how *args is transmitted
Second, local variables and global variables

For variables such as numbers and strings, changes in parameters inside the function do not affect the values of global variables outside the function

#局部变量的问题name = ' SYR ' def change_name (name):    print (' Before Change ', name)    name= ' SYR '    print (' After Change ', Name) change_name (name) print (name)

Execution Result:

Before Change SYR
After change Syr
SYR

If you are determined to change a global variable with the same name outside of the function, you can declare it inside the function

School= ' Cqput ' def Change (name):    Global school# can be modified in the function to    school= ' Cqput '    print (' before ' Name,school)    name= ' Syr '    print (' After Change ', name) (name) print (' School ', school) #局部变量前面加上global之后, You can modify the global variables

Execution Result:

Before Change SYR cqput
After change Syr
School Cqput

You can see that the shcool changes internally, and it changes the school directly outside the function.

But for arrays, dictionaries, and so on, the parameter changes inside the function are refracted directly outside the function.

#列表, collections, dictionaries these, modifications within functions also affect global variables names=[' sun ', ' Yue ', ' ru ']def change_names ():    names[0]= ' Sun '    print (names) change _names () print (names) #namse被修改

Execution Result:

[' Sun ', ' Yue ', ' ru ']
[' Sun ', ' Yue ', ' ru ']

Third, recursive functions and anonymous functions

Characteristics of Recursive functions:

    1. Must have a definite end condition
    2. Each time a deeper recursion is reached, the scale of the problem is lower than the last
    3. Recursive effect is very low, may lead to stack overflow (function call is implemented through the stack)

Simple Recursive example: two-point lookup

#Author: Yueru sundef binary_search (dataset,find_num):    print (DataSet)    if Len (DataSet) >1:        mid=int ( Len (DataSet)/2)        if Dataset[mid]==find_num:            print (' found%d, position%d '% (dataset[mid],mid))        elif Dataset[mid ]>find_num:            print (' The number to find is on the left of%d '%dataset[mid])            return Binary_search (dataset[0:mid],find_num)        else:            print (' The number to find on the right of%d '%dataset[mid])            return Binary_search (dataset[mid+1:],find_num)    else:        if Dataset[0]==find_num:            print (' Find number ')        else:            print (' Find failed ') # data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18 , (1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35],1) (35]binary_search)

Anonymous functions:

is the specified function that does not need to be displayed

Simple example:

#这段代码def Calc (n):    return N**nprint (calc) #换成匿名函数calc = Lambda n:n**nprint (Calc (10))

Combine map:

res = map (lambda x:x**2,[1,5,7,4,8]) for I in Res:    print (i)
Iv. higher-order functions

A higher order function is one function that receives another function as a parameter.

Simple example:

def add (x,y,f):    return F (x) + f (y)  res = Add (3,-6,abs) print (res)

Map of commonly used higher order functions:

>>> def f (x): ...     return x * x...>>> map (f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) [1, 4, 9, 16, 25, 36, 49, 64, 81]

Reduce of commonly used higher order functions:

>>> def add (x, y): ...     return x + y...>>> reduce (add, [1, 3, 5, 7, 9]) 25

Filter for high-order functions commonly used:

and map() similar, filter() also receive a function and a sequence. and map() different, the filter() incoming function is applied sequentially to each element, and then True False the element is persisted or discarded based on the return value

def is_odd (n):    return n% 2 = = 1filter (is_odd, [1, 2, 4, 5, 6, 9, 10, 15]) # results: [1, 5, 9, 15]

The sorted of high-order functions commonly used:

The sorted () function is also a high-order function, and it can also receive a key function to implement a custom sort, for example, by absolute size:

>>> sorted ([5, -12, 9, -21], key=abs) [5, 9,-12,-21, 36]

  

Five, function-type programming

Https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/ 0014317848428125ae6aa24068b4c50a7e71501ab275d52000

Python study notes the third day

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.