Common python functions and python Functions

Source: Internet
Author: User

Common python functions and python Functions

1. Introduction to Functions

Why is there a function? Because when writing code normally, if there is no function, there will be a lot of repeated code, so that the code reuse rate is relatively low... In addition, it is very difficult to maintain such code. To solve these problems, a function is used to encapsulate some frequently-seen code, in this way, you can call this function wherever you need to call this code.

Function Definition: A function encapsulates a set of statements by a name (function name). to execute this function, you only need to call its function name.

Features:

Code reuse
Maintain consistency
Scalability

2. Create a function

In python, The Function Definition Format is as follows:

Def function name (shape parameter): Internal code block of the function body

You can call a function by using the function name (real parameter.

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

  • The function name must start with an underscore (_) or a letter. It can contain any combination of letters, numbers, or underscores. You cannot use any punctuation marks;
  • Function names are case sensitive.
  • The function name cannot be a reserved word.

Differences between parameters and real parameters:

When defining a function, you can add parameters to the brackets behind the function name. These parameters are called form parameters. Form parameters are just codenamed.

Real parameters are the parameters in brackets after the function name when a function is called. The actual parameters must correspond to the actual parameters one by one. Otherwise, an error is returned when a function is called.

3. function parameters and return values

The parameters of the function must correspond to the actual parameters one by one:

  1. Required Parameter
  2. Keyword Parameter
  3. Default parameters
  4. Variable Length Parameter * args
  5. Variable Length Parameter ** kwargs

1. required parameters:

Parameters must be passed to the function one by one according to the corresponding relationship. The real parameters passed during function calling must correspond to the form parameters in the function definition one by one. There must be no more or less parameters, and the order must be the same.

Example:

Def f (name, age): print (name, age) f ("James", 18)

2. Keyword Parameters

A keyword parameter is a concept in a real parameter. When a function is called, it is declared that a parameter belongs to a certain keyword. When you use keyword parameters to allow function calls, the order of parameters is inconsistent with that during declaration, because the Python interpreter can use the parameter name to match the parameter value.

Example:

Def f (name, age): print (name, age) f (name = "James", 18)

3. Default Parameters

When a function is declared, the default value can be specified for a parameter. Such a parameter is called the default value. If no real parameter is received by default when a function is called, the default value is assigned to the parameter.

Example:

Def f (name, age, sex = "male"): print (name, age, sex) f (name = "James", 18)

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

4. Variable Length Parameter * args

In python, when a function is declared, (* variable name) can be used in parameters to accept parameters with uncertain length, however, in python, it is customary to use * args to accept parameters of an indefinite length, so that the parameters passed during function call can be of an indefinite length. After accepting the indefinite parameters, args puts these parameters in a tuple. You can access args to obtain these indefinite parameters.

Example:

Def f (* args): print (args) f ("James", 18, "male ")

The printed tuple contains the three elements ("James", 18, "male.

5. Variable Length Parameter ** kwargs

However, the preceding args can only receive unnamed parameters. What if there is a variable length parameter similar to a keyword parameter? In python, the variable name (** variable name) is used to receive variable parameters with an indefinite length. Similarly, python uses the ** kwargs to receive the indefinite name parameter. After receiving the variable length parameters, kwargs puts these parameters in a dictionary and obtains the corresponding parameter values through the key.

Example:

Def f (** kwargs): print (kwargs) f (name = "James", age = 18, sex = "male ")

After introducing these parameters, we will introduce the mixed use of these parameters:

What if a function uses all the preceding parameters? To avoid ambiguity, python stipulates that the following sequence of use rules should be followed if multiple parameters are mixed:

Def f (required parameter, default parameter, * args, ** kwargs ):
Pass
If both args and kwargs exist, The args is on the left.

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

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

If a list is to be passed to a function with an undefined parameter of an indefinite length, you can add * before the list to implement it, similarly, if you want to pass a dictionary to a function with an indefinite name parameter, you can add **

Example:

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

Function return value

To obtain the execution result of a function, you can use the return statement to return the result.

Note:

When a function encounters a return statement, it stops execution and returns the result. It can also be understood that the return statement indicates the end of the function. If the return statement is not specified in the function, the return value of this function is None.
Return multiple objects. The interpreter will assemble these objects into a single tuples and output the results one by one.

4. LEGB Scope

Python has four scopes:

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

E: enclosing: The local scope of nested parent functions, that is, the local scope of the upper-level functions that contain this function, but not global;

G: globa. global variables are defined at the module level;

B: built-in, variables in the system's fixed module, such as int and bytearray. The priority order of search variables is: local scope> outer scope> global in the current module> python built-in scope, that is, LEGB.

Local is relative to enclosing, And the enclosing variable is also local relative to the upper layer.

In Python, only modules, classes, and functions (def, lambda) introduce new scopes, and other code blocks (such as if, try, and) new scopes will not be introduced.

Modify the variable (errors are often displayed in the interview questions ):

X = 6 def f2 (): print (x) x = 5 f2 () # The cause of the error is that when print (x) is run, the interpreter will find it in a local scope, will find x = 5 (the function has been loaded to the memory), but x is used before the declaration, so the error is: # local variable 'X' referenced before assignment. how do I find x = 5? Simple: Comment out x = 5, x = 6 # the error is: name 'X' is not defined # Similarly, x = 6 def f2 (): x + = 1 # local variable 'X' referenced before assignment. f2 ()

Global keyword

When the internal scope wants to modify the variables of the external scope, the global and nonlocal keywords are used. When the modified variables are in the global scope, use global to declare the Code as follows:

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

Nonlocal keyword

The variables declared by the global keyword must be in the global scope and cannot be in the nested scope. What should I do if I want to modify the variables in the nested scope (enclosing scope, the outer layer is not in the global scope, in this case, the nonlocal keyword is required.

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

Summary

  • Variable Search sequence: LEGB, local scope> outer scope> global in current module> python built-in scope;
  • Only modules, classes, and functions can introduce new scopes;
  • For a variable, the internal scope declaration will overwrite the external variables. If it is not declared to be used directly, the variables in the external scope will be used;
  • When the value of an external scope variable is to be modified in the internal scope, the global keyword is used for the global variable, and the nonlocal keyword is used for the nested scope variable. Nonlocal Is The New Keyword of python3. With this keyword, closure can be perfectly implemented.

5. Special Functions

Recursive Function Definition: a recursive function calls itself within a function.

Sometimes, when solving some problems, the logic is complicated. At this time, you can consider using recursion, because the logic is clear when using recursive functions, which can solve some complicated problems. However, a problem with recursive functions is that if there are too many recursive calls, the calculation speed will be slow, and the default recursive call depth in python is 1000 layers, exceeding this layer will lead to "Stack explosion "... Therefore, we recommend that you do not use recursion whenever possible without recursion.

Example:

Def factorial (n): # use a loop to achieve Sum = 1 for I in range (2, n + 1): Sum * = I return Sum print (factorial (7 )) def recursive_factorial (n): # use recursion to implement the sum return (2 if n = 2 else n * recursive_factorial (n-1) print (recursive_factorial (7) def feibo (n ): # use recursion to implement the Fibonacci tangent sequence if n = 0 or n = 1: return n else: return feibo (n-1) + feibo (n-2) print (feibo (8 )) def feibo2 (n): # use a loop to implement the before, after = 0, 1 for I in range (n): before, after = after, before + after return before print (feibo2 (300 ))

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

Recursive features:

  • There must be a clear termination condition
  • Each time you enter a deeper layer of recursion, the problem scale should be reduced compared to the previous recursion.
  • If the recursion efficiency is not high, too many recursive layers will cause stack overflow (in the computer, function calls are implemented through the stack data structure. Every time a function is called, stack adds a layer of stack frames. Every time a function is returned, the stack will subtract a layer of stack frames. Because the stack size is not infinite, too many recursive calls may cause stack overflow .)

6. Functional Programming

I don't know much about functional programming, but there are four important built-in functions in python. Combining these functions can sometimes greatly 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

Execute function (item) in sequence for items in sequence, and make the items with the execution result of True into an iterator for filter object to return. It can be viewed 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 object iterator print (list (ret) # ['alvin ', 'balvin', 'calvin ', 'dalvin']

Execute function (item) in sequence for items in sequence, and form the execution result to be returned by a map object iterator. 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(10), 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)

Call the function sequentially for items in sequence. If starting_value exists, it can also be called as an initial value.

4 lambda

Comparison between common and anonymous functions:

# Normal function def add (a, B): return a + B print add (2, 3) # anonymous function add = lambda a, B: a + B print add (2, 3) #========= output =================== 5 5

The naming rules of anonymous functions are identified by the lamdba keyword. The left side of the colon (:) indicates the parameters (a, B) received by the function, and the right side of the colon (:) indicates the return value of the function (a + B ).

Because lamdba does not need to be named during creation, it is called an anonymous function.

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.