Python commonly used functions detailed _python

Source: Internet
Author: User
Tags anonymous function definition in python

1. Introduction to Functions

Why should there be a function? Because in the normal writing code, if there is no function, then there will be many duplicate code, so the code reuse rate is relatively low ... And this kind of code maintenance is also very difficult, in order to solve these problems, there is a function, used to encapsulate some of the frequently occurring code, so you can call this code in any place to call this function on the line.

function definition: A function is the collection of a set of statements by a name (function name) encapsulation, in order to execute this function, you can only call its functions name

Characteristics:

Code reuse
Maintain consistency
Scalability

2. Creation of functions

The function definition in Python is in the following format:

def function name (formal parameter):
 function Body Internal code block
 


function can be called using the function name (argument).

The naming rules for function names are the same as the naming rules for variables:

    • The function name must begin with an underscore or letter and can contain any combination of letters, numbers, or underscores. Cannot use any punctuation marks;
    • The name of the function is case-sensitive.
    • The function name cannot be a reserved word.

Difference between formal parameters and arguments:

When a function is defined, a parameter can be added to the parentheses following the function name, which is called the formal parameter, which is the formal argument, just a code name.

An argument is a parameter in parentheses following the function name when the function is invoked, and the formal parameter and the argument require one by one to correspond, otherwise the calling function will complain.

3. Function parameters and return values

As mentioned above, the formal parameters of a function correspond to the arguments, and the parameter pairs should have the following:

    1. Must be parameter
    2. Keyword parameters
    3. Default parameters
    4. Indefinite length parameter *args
    5. Indefinite length parameter **kwargs

1. Parameters must be:

The arguments must be passed into the function in a corresponding relationship, and the arguments passed by the function call must correspond to the formal parameter one by one when the function is defined, not more or less, and in the same order.

Give me a chestnut:

 def f (name,age):
   print (Name,age)
 f ("Xiaoming", 18)

2. Keyword parameters

A keyword parameter is a concept within an argument that declares a parameter to belong to a keyword when calling a function. The order of parameters when using keyword parameters to allow function calls is inconsistent with the Declaration, because the Python interpreter can match the parameter value with the argument name.

Give me a chestnut:

 def f (name,age):
   print (Name,age)
 f (name= "xiaoming", 18)

3. Default parameters

The default argument is that when the function is declared, you can assign a default value to a parameter, which is called the default value parameter. If the default parameter does not receive the corresponding argument when the function is invoked, the default value is assigned to this parameter.

Give me a chestnut:

 def f (name,age,sex= "male"):
   print (Name,age,sex)
 f (name= "xiaoming", 18)

In this way, the default parameter male is assigned to sex.

4. Indefinite length parameter *args

In Python, when a function is declared, a parameter can be used (* variable name) to accept parameters of indefinite length, but in python it is common to use *args to accept indefinite parameters, so that the parameters passed when the function is invoked can be indefinite lengths. After the args has accepted indefinite parameters, the parameters are placed in a tuple, which can be accessed by accessing args to obtain these indefinite parameters.

Give me a chestnut:

 def f (*args):
   print (args)
 f ("Xiaoming", "male")

Printed is a tuple, which contains ("Xiaoming", "male") these three elements.

5. Indefinite length parameter **kwargs

But the args can only receive unnamed parameters, what if there is an indefinite length parameter similar to the keyword parameter? Python Uses (* * variable name) to receive indefinite variable parameters. Similarly, Python also has the conventional use of **kwargs to receive indefinite long named parameters. After the Kwargs has received indefinite parameters, the parameters are placed in a dictionary, and the corresponding parameter values can be obtained by key.

Give me a chestnut:

 def f (**kwargs):
   print (Kwargs)
 f (name= "xiaoming", age=18,sex= "male")

After you've covered these parameters, here's what you'll want to do with the mix of these parameters:

What if a function uses all kinds of parameters above? In order not to create ambiguity, Python stipulates that if there are multiple parameters mixed, follow the following order of use rules:

def f (must parameters, default parameters, *args,**kwargs):
Pass
If args and Kwargs are present at the same time, args on the left.

The default parameter is to the right of the required argument, to the left of the *args

The position of the keyword parameter is not fixed (PS: The keyword parameter is not determined when the function is defined)

So, if you have a list that you want to pass into a function that has an indefinite length of unnamed arguments, you can add a * implementation to the list, and then, if you want to pass a dictionary into a function with an indefinite named parameter, you can precede the dictionary with a * *

Give me a chestnut:

 def f (*args,**kwargs):
   print (args) for
   i in Kwargs:
     print ("%s:%s"% (I,kwargs[i]))
 
 F (*[1,2,3],**{"a" : 1, "B": 2})

The return value of the function

To get the execution result of a function, you can return the result with the returned statement

Attention:

When a function encounters a return statement during execution, it stops execution and returns the result, or it can be understood that the return statement represents the end of the function. If you do not specify returns in the function, the returned value of this function is None
Return multiple objects, the interpreter assembles the multiple objects into a tuple as a whole output.

4.LEGB Scope

The scope in Python is divided into 4 different scenarios:

l:local, local scope, that is, the variables defined in the function;

E:enclosing, the local scope of the nested parent function, that is, the local scope of the ancestor function that contains the function, but is not global;

G:globa, global variable, is the module level defined variables;

B:built-in, the system fixed the variables inside the module, such as int, ByteArray and so on. The order of precedence of the search variables is: scope local > Outer scope > The Global >python built-in scope in the current module, that is, LEGB.

Local and enclosing are relative, and enclosing variables are also local to the upper level.

In Python, only modules (module), Class (Class), and functions (Def, Lambda) introduce new scopes, and other blocks of code (such as if, try, for, and so on) do not introduce new scopes.

Variable modification (Error modification, often out of the face test):

 X=6
 def f2 ():
   print (x)
   x=5
 F2 ()
 
 # The reason for the error is that when print (x), the interpreter finds the x=5 (the function has been loaded into memory) in the local scope, but X is used before the declaration, So the error:
 # local variable ' x ' referenced before assignment. How can you prove that you found x=5? Simple: Comment out x=5,x=6
 # Error: Name ' x ' is not defined
    #同理
 x=6
 def f2 ():
   x+=1 #local variable ' x ' referenced before.
 F2 ()

Global keyword

When an internal scope wants to modify the variables of an external scope, the global and nonlocal keywords are used, and when the modified variable is on the global scope, it is necessary to use global to declare the code as follows:

 Count = ten
 def outer ():
   Global Count
   print (count) 
   count =
   print (count)
 outer ()

nonlocal keyword

The variables declared by the Global keyword must be on the global scope and cannot be nested on the scope, so when you want to modify the variables in the nested scope (enclosing scope, outer non-global scope), you need the nonlocal keyword.

 def outer ():
   count = ten
   def inner ():
     nonlocal count
     count =
     print (count)
   inner ()
   print (count)
 outer ()

Summary

    • Variable lookup order: LEGB, scope local > Outer scope > Global >python built-in scope in current module;
    • Only modules, classes, and functions can introduce new scopes;
    • For a variable, the internal scope first declares that it overwrites the external variable, and does not declare that it uses the outer scope variables.
    • Internal scope to modify the value of an external scope variable, a global variable uses the global keyword, and the nested scope variable uses the nonlocal keyword. Nonlocal is python3 new keyword, with this keyword, you can achieve the perfect closure.

5. Special functions

Recursive function definition: recursive function is to call itself inside a function

Sometimes when solving some problems, the logic is more complex, this time can consider using recursion, because the use of recursive functions, logic is clearer, can solve some more complex problems. But the problem with recursive functions is that if recursion calls itself more often, it will make the computation slow, and in Python the default recursive call depth is 1000 layers, which will lead to a "burst stack" ... Therefore, it is advisable not to use recursion when it is possible to do so without recursion.

Give me a chestnut:

 def factorial (n): # using Loops to implement summation
   sum=1 for
   i in range (2,n+1):
     sum*=i return
   Sum
 print (factorial (7))
 
 def recursive_factorial (n): # Use recursion to implement sum return
   (2 if n==2 else n*recursive_factorial (n-1))
 
 print (recursive _factorial (7))
 
 def Feibo (n): # using recursion to implement Fibonacci that tangent sequence
   if n==0 or N==1:return n
   else:return Feibo (n-1) +feibo (n-2) C12/>print (Feibo (8))
 
 def feibo2 (n): # using Loops to implement Fibonacci that tangent sequence
   before,after=0,1
   for I in Range (n):
     before, After=after,before+after return
   before
 print (Feibo2 (300))

The advantages of recursive functions: simple definition, clear logic. Theoretically, all recursive functions can be written as loops, but the logic of loops is not as clear as recursion.

Recursive attributes:

    • Must have a definite end condition
    • Each time you enter a deeper level of recursion, the scale of the problem should be less than the last recursion.
    • Recursive efficiency is not high, too many recursive levels will lead to stack overflow (in the computer, the function call is through the stack (stack) of this data structure, every time into a function call, the stack will add a layer of stack frame, whenever the function returns, the stack will be reduced by a stack frame. Because the size of the stack is not infinite, the number of recursive calls can be excessive, resulting in stack overflow. )

6. Functional programming

I don't understand very much about functional programming, but there are 4 of the more important built-in functions in python that can be used in combination to improve programming efficiency.

1 filter (function, sequence)

 str = [' A ', ' B ', ' C ', ' d ']
 def fun1 (s):
   if S!= ' a ': return
     s
 ret = filter (FUN1, str)
Print (list (ret)) # RET is an iterator object

Performs a function (item) on the item in sequence, and returns an iterator that executes the item with the result of true to a filter object. Can be considered as a filter function.

2 map (function, sequence)

 str = [1, 2, ' A ', ' B ']
 def fun2 (s): return
   S + "Alvin"
 ret = map (fun2, str)
 print (ret)   # Map Objec T's iterator
 print (list (ret)) # [' Aalvin ', ' Balvin ', ' Calvin ', ' Dalvin ']

Executes the function (item) of the item in sequence, and the execution result is returned as a map object iterator. The map also supports multiple sequence, which requires that the function also supports the corresponding number of parameter inputs:

 def add (x,y): return
   x+y
 print (list (map (add, range, range (10)) ##[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

3 reduce (function, sequence, starting_value)

 From Functools import reduce
 def add1 (x,y): return
   x + y
 
 print (Reduce (ADD1, range (1, 101)) # # 4950 (Note: 1+2+ ...) . +99)
 print (Reduce (ADD1, range (1, 101), 20)) # # 4970 (Note: 1+2+...+99+20)

The call function is iterated over the item order in sequence, and can be invoked as an initial value if there is a starting_value.

4 Lambda

Comparison of common functions with anonymous functions:

 #普通函数
 def Add (a,b): return
   A + B
 
 print Add (2,3)
 
 
 #匿名函数
 add = lambda a,b:a + b
 Print Add (2,3 )
 
 
 #======== output ===========
 5
 5

The naming rule for anonymous functions, identified by the LAMDBA keyword, the left side of the colon (:) represents the parameter received by the function (A,b), and the right side of the colon (:) represents the return value of the function (A+B).

Because LAMDBA does not need to be named when it is created, it is called an anonymous function

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.