python is often used for function elaboration

  • 2020-05-10 18:28:30
  • OfStack

1. Introduction of functions

Why have a function? Because when writing code, if there is no function, there will be a lot of repetitive code, so the code reuse rate is low. And such code is very difficult to maintain, in order to solve these problems, there are functions to encapsulate 1 of the frequently occurring code, so that you can call the function wherever you need to call this code.

Function definition: function refers to the collection of 1 group of statements through a name (function name) wrapped, to execute this function, just call its function name

Features:

Code reuse
It's going to be 1
scalability

2. Function creation

The format of the function definition in python is as follows:


def  The function name ( parameter ):
  Function body internal code block 
 


Function calls can be made using the function name (argument).

The naming rules for function names and variables are as follows:

Function names must be underlined or begin with a letter, and can contain any combination of letters, Numbers, or underscores. You can't use any punctuation; Function names are case sensitive. The function name cannot be a reserved word.

Difference between formal parameter and argument:

When a function is defined, parameters can be added to the parentheses after the function name. These parameters are called formal parameters.

Arguments are the arguments in parentheses after the name of a function when it is called. Formal arguments and arguments need to correspond to 11, otherwise the calling function will report an error.

3. Function parameters and return values

As mentioned above, the formal parameter and the argument of the function should correspond to 11, so the parameter pairs should be as follows:

Parameters must be Keyword parameter The default parameters Variable length parameter *args Variable length parameter **kwargs

1. Required parameters:

Must parameters must be passed into the function one by one in the corresponding relationship, and the arguments passed when the function is called must correspond to the formal parameters 11 when the function is defined, no more and no less, and the order must be 1 to 1.

Take a chestnut:


 def f(name,age):
   print(name,age)
 f(" Xiao Ming ",18)

2. Keyword parameters

Keyword arguments are the concepts in arguments that declare that a parameter belongs to a keyword when a function is called. The use of keyword arguments allows a function to call arguments in a different order than when they were declared, because the Python interpreter can match parameter values with parameter names.

Take a chestnut:


 def f(name,age):
   print(name,age)
 f(name=" Xiao Ming ",18)

3. Default parameters

The default parameter is when the function is declared, you can specify a default value for a parameter. Such a parameter is called a default parameter. If the default parameter does not receive a corresponding argument when the function is called, the default value is assigned to the parameter.

Take a chestnut:


 def f(name,age,sex="male"):
   print(name,age,sex)
 f(name=" Xiao Ming ",18)

This will assign the default parameter male to sex.

4. Variable length parameter *args

In python, when the function is declared, the parameter can be used (* variable name) to accept the parameter of uncertain length, but in python, it is common practice to use *args to accept the parameter of indefinite length, so that the parameter passed when the function is called can be of indefinite length. Once args accepts the variable length parameters, place them in an tuple and access args to obtain the variable length parameters.

Take a chestnut:


 def f(*args):
   print(args)
 f(" Xiao Ming ",18,"male")

The print is an tuple containing the three elements (" xiao Ming ", "18", "male").

5. Variable length parameter **kwargs

But args above can only accept unnamed parameters, so what if there are variable length parameters similar to keyword parameters? python USES (** variable name) to receive variable arguments of variable length. Similarly, **kwargs is used to receive variable length named parameters in python. After kwargs receives the variable length parameters, it puts them into a dictionary and can get the corresponding parameter values through key.

Take a chestnut:


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

After the introduction of these parameters, the following is about the mixed use of these parameters:

What if a function takes all of the above types of arguments? In order to avoid ambiguity, python stipulates that if multiple parameters are mixed, the following rules should be followed:

  def f(required parameter, default parameter,*args,**kwargs) :
        pass
If args and kwargs exist at the same time, args is on the left

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

The location of keyword parameters is not fixed (ps: keyword parameters are not determined when the function is defined)

So, if you have a list that you want to pass into a function with an unnamed parameter of indefinite length, you can do that by putting * in front of the list. Similarly, if you want to pass a dictionary into a function with an unnamed parameter of indefinite length, you can put ** in front of the dictionary

Take 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 result of a function's execution, you can use the return statement to return the result

Note:

As soon as the function encounters an return statement during execution, it will stop execution and return the result. It can also be understood that the return statement represents the end of the function. If return is not specified in the function, the return value of this function is None
return multiple objects, which the interpreter assembles into one tuple and outputs as one overall result.

4. LEGB scope

The scope of python is divided into four cases:

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 parent function containing the function, but not global;

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

B: built-in, variables in the system fixed module, such as int, bytearray, etc. The priority order of search variables is: local scope > Outer scope > Global in the current module > The python built-in scope is LEGB.

local is relative to enclosing, and enclosing is also local relative to the upper level.

In Python, only modules (module), classes (class), and functions (def, lambda) will introduce new scopes. Other code blocks (if, try, for, and so on) will not introduce new scopes.

Modification of variables (error modification, frequently used in interview questions) :


 x=6
 def f2():
   print(x)
   x=5
 f2()
 
 #  Here's why it's wrong print(x) when , The interpreter will look at the local scope , Will find x=5( The function has been loaded into memory ), but x Used before the declaration , So an error :
 # local variable 'x' referenced before assignment. How do you prove it x=5 ? ? simple : Comment out the x=5,x=6
 #  An error for :name 'x' is not defined
 # In the same way 
 x=6
 def f2():
   x+=1 #local variable 'x' referenced before assignment.
 f2()

global keyword

The global and nonlocal keywords are used when the internal scope wants to modify the variable of the external scope. When the modified variable is in the global scope (global scope), global is used to declare 1 first. The code is as follows:


 count = 10
 def outer():
   global count
   print(count) 
   count = 100
   print(count)
 outer()

nonlocal keyword

Variables declared by the global keyword must be in the global scope and cannot be nested in the scope. What if you want to modify variables in the nested scope (enclosing scope, outer non-global scope), then you need the nonlocal keyword


 def outer():
   count = 10
   def inner():
     nonlocal count
     count = 20
     print(count)
   inner()
   print(count)
 outer()

summary

Variable search order: LEGB, local scope > Outer scope > Global in the current module > python built-in scope; Only modules, classes, and functions can introduce new scopes; For a variable, the internal scope is declared first to override the external variable, and if it is not declared to be used directly, the external scope variable will be used. When an internal scope modifies the value of an external scope variable, the global keyword is used for global variables, and the nonlocal keyword is used for nested scope variables. nonlocal is a new keyword for python3, and with this keyword, closures are perfectly implemented.

5. Special functions

Recursive function definition: a recursive function calls itself inside a function

Sometimes when you're trying to solve some problems, the logic is a little bit more complicated, so you can think about using recursion, because if you're using recursive functions, the logic is a little bit clearer, and you can solve some complicated problems. One problem with recursive functions is that if they call themselves more often, the computation will be slow. Moreover, the default recursive call depth in python is 1000 layers, and exceeding this level will lead to "stack explosion". Therefore, it is recommended not to use recursion when you can avoid recursion.

Take a chestnut:


 def f(name,age):
   print(name,age)
 f(" Xiao Ming ",18)
0

Advantages of recursive functions: simple definition, clear logic. In theory, all recursive functions can be written in a loop, but the logic of the loop is not as clear as that of the recursion.

Recursive features:

There must be a clear end condition Each time you go to the next level of recursion, the problem should be smaller than it was the last time Recursive efficiency is not high, too many recursive layers will lead to stack overflow (in the computer, function call is through the stack (stack) this data structure, every time into a function call, the stack will add 1 layer of stack frame, every time the function back, the stack will subtract 1 layer of stack frame. Since the size of the stack is not infinite, too many recursive calls can cause the stack to overflow.

6. Functional programming

I don't know much about functional programming, but there are four important built-in functions in python that can be used in combination to improve programming efficiency.


 def f(name,age):
   print(name,age)
 f(" Xiao Ming ",18)
1

function(item) is executed for item in sequence in turn, and item whose result is True is made into an iterator of filter object. You can think of it as a filter function.

2 map(function, sequence)


 def f(name,age):
   print(name,age)
 f(" Xiao Ming ",18)
2

function(item) is executed for item in sequence, and the results are returned as one map object iterator. map also supports multiple sequence, which requires function to support a corresponding number of parameter inputs:


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

3 reduce(function, sequence, starting_value)


 def f(name,age):
   print(name,age)
 f(" Xiao Ming ",18)
4

Call function for item in sequence sequential iteration, or as an initial value if you have starting_value.

4 lambda

Comparison between ordinary functions and anonymous functions:


 def f(name,age):
   print(name,age)
 f(" Xiao Ming ",18)
5

The naming convention for anonymous functions, identified by the lamdba keyword, with the colon (:) to the left representing the parameters received by the function (a,b), and the colon (:) to the right representing the return value of the function (a+b).

Because lamdba does not need a name when it is created, it is called an anonymous function


Related articles: