The first knowledge of Python (9) __python function

Source: Internet
Author: User

Function

Reference:

#########################################################

Http://www.w3cschool.cc/python/python-functions.html

Http://developer.51cto.com/art/200809/88052.htm

Http://www.pythondoc.com/pythontutorial27/controlflow.html#tut-functions

Http://see.xidian.edu.cn/cpp/html/1829.html

Http://www.cnblogs.com/linyawen/archive/2011/10/01/2196957.html

#########################################################

What is a function?

In layman's terms, a function is a group of statements that accomplishes a particular function, which can be used as a unit and give it a name, so that we can execute it multiple times in different places of the program through the function name (often called a function call), without having to repeat the statements everywhere.

Why use a function?

This is mainly due to two considerations:

1. To reduce the difficulty of programming, it is common to break down a complex big problem into a series of simpler small problems, and then continue to divide small problems into smaller problems that we can divide and conquer when the problem is simple enough. At this point, we can use the function to deal with specific problems, each small problem solved, the big problem will be solved.

2. Code reuse. The functions we define can be used in multiple locations of a program or in multiple programs. In addition, we can put functions in one module for other programmers to use, and we can also use other programmer-defined functions. This avoids duplication of effort and provides efficiency.

My understanding: function is through a one-time labor, write good one can complete a specific function of the statement block, so the next need this function, as long as the call this block of the statement is good, do not need to write again this statement block, improve efficiency!

Defining functions

Custom Function Rules:

    • The function code block begins with a def keyword followed by the function identifier name and parentheses ().
    • Any incoming parameters and arguments must be placed in the middle of the parentheses. Parentheses can be used to define parameters.
    • The first line of the function statement can optionally use the document string-for storing the function description.
    • The function contents begin with a colon and are indented.
    • Return[expression] End Function, optionally returning a value to the caller. Return without an expression is equivalent to returning None.

def   function name (argument list):    function Body
    • The function name can be any valid Python identifier;
    • The argument list is the value passed to it when the function is called, and can consist of multiple, one, or 0 parameters, separated by commas when there are multiple parameters;
    • Parentheses are essential, even without parameters, without it;
    • The function body is the code that executes every time the function is called, can consist of a statement or multiple statements, the function body must pay attention to indentation;
    • You cannot forget the colon after the parentheses, which can cause syntax errors
 >>> def  fib (n): #   Write Fibonacci series up to n  ...  print a Fibonacci series up to N.      #   ... a, b = 0, 1 ...  while  a < N: ...  print   A,... A, b  = B, A+b ...  >>> #   now call the function we just Defined:  ... fib (2000) 0  1 1 2 3 5 8 144 233 377 610 987 1597

function parameters

Reference: http://www.cnblogs.com/tqsummer/archive/2011/01/25/1944416.html

default parameter ( default parameter): When a function is called, the value of the default parameter is considered to be the default value if it is not passed in.

def taxme (cost,rate=0.0825): ... return cost+ (cost * rate ) ... >>> taxme (108.25>>>)>>> taxme (0.05)

But remember: all the required parameters precede the default parameters. If the parameters are not given in the correct order, a syntax error is generated.

def taxMe2 (rate=0.0825return cost * (1.0 + rate ) ... Syntaxerror:non-default argument follows default argument

Important WARNING: The default value is only assigned once. This makes it different when the default value is a Mutable object, such as a list, a dictionary, or an instance of most classes. For example, the following function accumulates (before) the arguments passed to it during subsequent calls:

def F (A, l=[]):    l.append (a)    return  Lprint f (1)  print F (2) print F (3) This will be printed: [1][1,2] [1, 2, 3]

If you do not want to share the default values in subsequent calls, you can write the function like this:

def F (A, l=none):    if is none:        = []    L.append (a)    return L
keyword parameters:We use the name (the keyword) instead of the location to specify the parameters of the function. When calling a function, the parameters passed are matched to the parameter table in the function definition according to the position (the normal parameter is called the positional parameter), such as FUNCB (100, 99) and FUNCB (99, 100) are not the same execution result. Sometimes, if the parameters are too many in order to be remembered, the parameter names are used to provide a way to resolve them. That is, when the function is called, use formal parameter name = argument nameThe way to pass parameters such as FUNCB (a=100, b=99) and FUNCB (b=99, a=100), the results are the same.

Keyword parameter features:

One is that it is easy to use functions because we do not need to worry about the order of the parameters.

Second, if other parameters have default parameter values, we can only assign values to the parameters we want to assign.

For example:

def func (A, b=5, c=10):    print('a ' is ' and ' B ' is  " and C for ', c)func (3, 7)func (c=24) func ( C=50, a=100) output: A for 3 and B for 7 and C for 10a for 25 and B for 5 and C for 24a 100 and B for 5 and C for

How it works:

A function named Func has a parameter with no default parameter value, and the following two parameters have default parameter values.

For the first time, Func (3, 7) is used, parameter A is given a value of 3, parameter B is given a value of 7, and parameter C is given the default value of 10.

For the second use of Func (c=24), parameter A is given a value of 25 according to the position of the parameter, and the parameter C is given a value of 24 according to the parameter name, which is the parameter keyword, and the variable B gets the default value of 5.

The third time using Func (c=50, a=100), we used the parameter keyword for all given values. Note that we specify the value for parameter C before the parameter A, although in the function definition A is before C.

My understanding: About default parameters and keyword parameters

The default argument is a formal parameter when defining a function, which is used when defining a function.

The keyword argument is an argument that is invoked when the function is called.

Variable parameters:

with an asterisk * The parameters:

If you are unsure of the number of parameters, you need to take the parameter with * to accept the extra arguments, for example:

def Funcd (A, B, *c):  print  a  print  b  Print  "" % len (c)  print  c#  Call FUNCD (1, 2, 3, 4, 5, 6) The result is : 4(3, 4, 5, 6

As we can see, the first two parameters are accepted by a, B, and the remaining 4 parameters are all accepted by C, and C is a tuple here. When we call FUNCD, we have to pass at least 2 parameters, 2 or more parameters, put in C, if there are only two parameters, then C is an empty tuple.

with two asterisk * * The parameters:

If the last formal parameter in a function definition has a * * (double star) prefix, all other keyword parameters other than the normal parameter will be placed in a dictionary passed to the function, such as:

def FUNCF (A, * *b)  :print  a  for in  B:     print"" + str (b[x])# call FUNCF (c= ') Hello ', b=200), execution result 200

As you can see, B is a Dict object instance that accepts the keyword arguments B and c.

My understanding: About mutable Parameters

We sometimes take arguments when invoking arguments, and extra non-keyword parameters are received by an asterisk parameter, which becomes a tuple, the keyword parameter, because there is an equal sign, so there are two values, it needs to be received by the two asterisk parameter as a dictionary.

anonymous function lambda

Reference: http://www.cnblogs.com/linyawen/archive/2011/10/01/2196957.html

A complete lambda "statement" represents an expression in which the body of the expression must be placed on the same line as the declaration. Let's now demonstrate the syntax of the anonymous function:

Lambda [arg1[, Arg2, ... ArgN]: expression

In a lambda statement, the colon is preceded by a parameter, which can have multiple, separated by commas, and a return value to the right of the colon.

For example:

def f (x): return x**2print f (4)#python using lambda, write this:Lambda x:x**2Print g (4)

The default parameters can also be used in lambda parameters, just as they are used in def.

>>>x = (lambda"fee" "fie " " Foe": A + B +c)>>>x ("wee")'  weefiefoe'

Lambda Features:

1. When using Python to write some execution scripts, using lambda eliminates the process of defining a function and makes the code more streamlined.

2. For some abstract functions that are not reused elsewhere, sometimes it is difficult to name a function, and using lambda does not have to consider naming problems.

3. Using lambda makes the code easier to understand at some point.

Built-in functions

Filter ()

Filter (BOOL_FUNC,SEQ): This function is equivalent to a filter. Call a Boolean function Bool_func to iterate through the elements in each SEQ, and return a sequence of elements that enable BOOL_SEQ to return a value of true.

>>> Filter (lambda x:x%2 = = 0,[1,2,3,4,5]) [2, 4]

Map ()

Map (FUNC,SEQ1[,SEQ2 ...]) : The function func acts on each element of a given sequence and provides the return value with a list, and if Func is none,func as an identity function, returns a list of n tuples containing the set of elements in each sequence.

>>> Map (Lambdax:none,[1,2,3,4]) [None, none, none, none]>>> Map (LambdaX:X * 2,[1,2,3,4]) [2, 4, 6, 8] >>> Map (LambdaX:X * 2,[1,2,3,4,[5,6,7]]) [2, 4, 6, 8, [5, 6, 7, 5, 6, 7]] >>> Map (LambdaX,y:x + y, [1,3,5],[2,4,6])[3, 7, 11]>>> Map (LambdaX, Y: (x+y, X-y), [1,3,5], [2,4,6])[(3,-1), (7,-1), (11,-1)]>>> Map (Lambdax:none,[1,2,3,4, [5,6,7]] [None, none, none, none, none]

Reduce

Reduce (Func,seq[,init]): Func is a two-tuple function that functions func on the elements of a SEQ sequence, each carrying a pair (the previous result and the element of the next sequence), continuously acting on the resulting subsequent result with the existing result and the next value, Finally, we reduce our sequence to a single return value: If Init is given, the first comparison will be init and the first sequence element instead of the head two elements of the sequence.

>>> reduce (lambda x,y:x + y,[1,2,3,4>>> reduce (lambda x,y:x + y,[1,2,3 , 4],1020>>> reduce (lambda x,y:x*y,[1,2,3,4])24

Global variables and local variables

Local variables

The variables you declare in the function definition have nothing to do with other variables of the same name that are used outside the function, that is, the variable name is local to the function. This is called the range of the variable. All variables have a range of blocks that they declare, starting at the point defined by the name.

Examples of local variable definitions:

x =def  func (    x):print('x equals ', x)    = 2    Print (' local variable x changed to ', X ' func (x) Print ('x has always been '

How it works:

For the first time, we use the first line of the function body to print the value of the variable x, and Python uses the arguments declared on the function definition in the main block.

Next, we assign X to 2, and the variable to x is a local variable for our function, so the variable x defined in the main block is not affected when we change the value of x in the function.

The last call to the print function, which displays the variable x defined in the main block, confirms that it is not affected by the local variable that called the function earlier.

If the name of the global variable is declared in a function body, the name of the global variable can be overwritten by the local variable.

Using global declarations

If you want to assign a value to a variable defined in the top-level program (that is, not within any type of scope such as a function or class), you must tell Python that the variable is not local but global. We use the global statement, it is not possible to assign a global statement to a variable defined outside the function.

You can use the values of the variables defined outside the function (assuming there are no variables with the same name within the function). However, this is not encouraged and should be avoided because it makes the reader of the program unclear where the variable is defined, and using the global statement is very clear that the variable is defined in one of the most outer blocks.

Examples of using global variables:

x =def  func ()    :Global  x    print(the value of ' x is  '  , x)    = 2    print(' global variable x changed to ', X) func ()  Print(The value of ' x is ', x)# output:

How it works:

The global statement is used to declare that x is a global variable, and when we assign a value to x within a function, its change maps to the value of the x we use in the main block.

You can specify multiple global variables with the same global statement, such as: Global X, Y, Z

The first knowledge of Python (9) __python 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.