Python -- 3, function, python -- 3 Function

Source: Internet
Author: User
Tags variable scope

Python -- 3, function, python -- 3 Function
Definition:

When defining a function, it is also equivalent to defining a variable. The code in the function body is stored in the opened memory space. When a function is used, it is declared as a function through func (), and its corresponding value is code. 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:

In Python, define a function to usedefStatement, write the function name, parameters in parentheses, and colons in sequence:Then, write the function body in the indent block. The return value of the function isreturnStatement.

Parameters passed in the function can be values of any data type. Parameters are divided into real parameters and form parameters.

Real parameters and form parameters

The Parameter Variable allocates memory units only when called. The allocated memory units are immediately released at the end of the call. Therefore, the parameter is valid only within the function. After the function call ends, you cannot use this variable after the main function is called.

Real parameters can be constants, variables, expressions, functions, etc. No matter what type of real parameters are, they must have a definite value during function calling, in order to pass these values to the form parameter. Therefore, values should be pre-assigned, input, and other methods to obtain a definite value for the parameter.

 

We use a custom one to calculate the absolute valuefuncFunction example:

def func(x):    if x >= 0:        return x    else:        return -x

Note: When executing a statement in the function bodyreturnThe function is executed and the result is returned. Therefore, functions can implement complex logic through conditional judgment and loops.

If noreturnStatement. After the function is executed, the result is returned, but the result isNone.

return NoneCan be abbreviatedreturn.

Return returns multiple values.

Return x, y

The returned value is a tuple! However, in syntax, a tuple can be returned without parentheses, while multiple variables can receive a tuple at the same time and assign the corresponding value by position, A Python function returns a tuple, but it is easier to write.

 

Empty functions and their functions
def func1():    pass

Pass indicates that nothing is done during execution. But MissingpassWhen the code is run, a syntax error occurs.

The definition of empty functions is to clearly define the required functions when writing the program framework.

Summary

When defining a function, you must determine the function name and number of parameters;

If necessary, check the data type of the parameter;

The function body can be used internally.returnReturns function results at any time;

No function execution completedreturnStatement, automaticallyreturn None.

A function can return multiple values at the same time, but it is actually a tuple.

Function Parameters

In addition to the required parameters, you can also use default parameters, variable parameters, and keyword parameters, so that the interface defined by the function can not only process complex parameters, it also simplifies the caller's code.

Parameter check

When calling a function, if the number of parameters is incorrect, the Python interpreter automatically checks the number and throwsTypeError。

However, if the parameter type is incorrect, the Python interpreter cannot help us check the parameter type.

Default parameters

The following example shows how to define the default parameters of a function. First, write a function to calculate x2:

def power(x):    return x * x

When we callpowerA function must be input with only one parameter.x:

>>> power(5)25>>> power(15)225

What if we want to calculate x3? You can define anotherpower3Function, but if you want to calculate x4, x5 ...... What should I do? We cannot define an infinite number of functions.

You may have thoughtpower(x)Changepower(x, n)To calculate xn, just do it:

def power(x, n):    s = 1    while n > 0:        n = n - 1        s = s * x    return s

For the modifiedpowerFunction, which can calculate any nth power:

>>> power(5, 2)25>>> power(5, 3)125

However, when the call code is entered with only the value of x, the call will fail. Because a parameter is added, the call will fail.

 

In this case, the default parameters are used. Since we often calculate x2, we can set the default value of the second parameter n to 2:

def power(x, n=2):    s = 1    while n > 0:        n = n - 1        s = s * x    return s

In this way, when we callpower(5)Is equivalent to callingpower(5, 2):

>>> power(5)25>>> power(5, 2)25

Forn > 2In other cases, you must explicitly input n, suchpower(5, 3).

As shown in the preceding example, the default parameters can simplify function calls. Note the following when setting default parameters:

First, the required parameter is in the front, and the default parameter is in the back; otherwise, the Python interpreter reports an error (think about why the default parameter cannot be placed before the required parameter );

Second, set the default parameters.

When a function has multiple parameters, place the parameters with major changes first and those with minor changes later. A parameter with a small change can be used as the default parameter.

What are the advantages of using default parameters? The biggest benefit is that it can reduce the difficulty of calling a function.

When multiple default parameters exist, the default parameters can be provided in sequence.

However

The default parameter has the largest pitfall, as shown below:

Define a function, input a list, and addENDThen return:

def add_end(L=[]):    L.append('END')    return L

When you call it normally, the results seem to be good:

>>> add_end([1, 2, 3])[1, 2, 3, 'END']>>> add_end(['x', 'y', 'z'])['x', 'y', 'z', 'END']

When you use the default parameter call, the initial result is also correct:

>>> add_end()['END']

Howeveradd_end()The result is incorrect:

>>> add_end()['END', 'END']>>> add_end()['END', 'END', 'END']

Many beginners are confused. The default parameter is[]But the function seems to "remember" every time it was added'END'.

The reasons are as follows:

When defining a Python function, the default parameterLIs calculated, that is[]Because the default parametersLIt is also a variable that points to the object[]. If this function is called every timeLThe content of the default parameter changes next time, instead of when the function is defined.[].

Therefore, to define default parameters, remember that the default parameters must point to unchanged objects!

Note: the purpose of designing a non-changing object such as str and None is as follows: Once a non-changing object is created, the internal data of the object cannot be modified, which reduces errors caused by data modification. In addition, because the object remains unchanged, there is no need to lock the object to be read at the same time in the multi-task environment. When writing a program, if we can design a constant object, we should try to design it as a constant object.

Variable parameters

Variable parameters can also be defined in Python functions. As the name suggests, a variable parameter means that the number of input parameters is variable, which can be 1, 2 to any, or 0.

Let's use a mathematical example to give a group of numbers a, B, c ......, Calculate a2 + b2 + c2 + .......

To define this function, we must determine the input parameters. Because the number of parameters is unknown, We can first consider a, B, c ...... As a list or tuple, the function can be defined as follows:

def calc(numbers):    sum = 0    for n in numbers:        sum = sum + n * n    return sum

However, you need to first assemble a list or tuple:

>>> calc([1, 2, 3])14>>> calc((1, 3, 5, 7))84

If variable parameters are used, the method of calling a function can be simplified as follows:

>>> calc(1, 2, 3)14>>> calc(1, 3, 5, 7)84

Therefore, we change the function parameters to variable parameters:

def calc(*numbers):    sum = 0    for n in numbers:        sum = sum + n * n    return sum

Compared with defining the list or tuple parameter, defining variable parameters only adds*. Inside the function, the parameternumbersA tuple is received, so the function code remains unchanged. However, when calling this function, you can input any parameter, including 0 parameters:

>>> calc(1, 2)5>>> calc()0

If a list or tuple already exists, what should I do if I want to call a variable parameter? You can do this:

>>> nums = [1, 2, 3]>>> calc(nums[0], nums[1], nums[2])14

This method is feasible, and the problem is too cumbersome. Therefore, Python allows you to add*To change the list or tuple element to a variable parameter:

>>> nums = [1, 2, 3]>>> calc(*nums)14

This method is quite useful and common.

Keyword Parameter

Variable parameters allow you to input 0 or any parameter. These variable parameters are automatically assembled into a tuple during function calling. Keyword parameters allow you to input 0 or any parameters with parameter names. These keyword parameters are automatically assembled into a dict in the function. See the example:

def person(name, age, **kw):    print 'name:', name, 'age:', age, 'other:', kw

FunctionpersonExcept for required parametersnameAndageIn addition, keyword parameters are also accepted.kw. When calling this function, you can only input the required parameters:

>>> person('Michael', 30)name: Michael age: 30 other: {}

You can also input any number of keyword parameters:

>>> person('Bob', 35, city='Beijing')name: Bob age: 35 other: {'city': 'Beijing'}>>> person('Adam', 45, gender='M', job='Engineer')name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}

What is the use of keyword parameters? It can expand functions of functions. For examplepersonIn the function, we ensure that we can receivenameAndageHowever, if the caller is willing to provide more parameters, we can also receive them. Imagine that you are working on a user registration function. Except that the user name and age are mandatory, other functions are optional. Using Keyword parameters to define this function can meet the registration requirements.

Similar to variable parameters, You can assemble a dict and then convert the dict into a keyword parameter:

>>> kw = {'city': 'Beijing', 'job': 'Engineer'}>>> person('Jack', 24, city=kw['city'], job=kw['job'])name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}

Of course, the above complex calls can be simplified:

>>> kw = {'city': 'Beijing', 'job': 'Engineer'}>>> person('Jack', 24, **kw)name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}
Parameter combination

Define functions in Python. You can use required parameters, default parameters, variable parameters, and keyword parameters. These four parameters can be used together or only use some of them, the order of parameter definitions must be: mandatory parameter, default parameter, variable parameter, and keyword parameter.

For example, defining a function includes the preceding four parameters:

def func(a, b, c=0, *args, **kw):    print 'a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw

When a function is called, the Python interpreter automatically transmits the corresponding parameters according to the parameter location and parameter name.

>>> func(1, 2)a = 1 b = 2 c = 0 args = () kw = {}>>> func(1, 2, c=3)a = 1 b = 2 c = 3 args = () kw = {}>>> func(1, 2, 3, 'a', 'b')a = 1 b = 2 c = 3 args = ('a', 'b') kw = {}>>> func(1, 2, 3, 'a', 'b', x=99)a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99}

The most amazing thing is that through a tuple and dict, you can also call this function:

>>> args = (1, 2, 3, 4)>>> kw = {'x': 99}>>> func(*args, **kw)a = 1 b = 2 c = 3 args = (4,) kw = {'x': 99}

Therefore, for any functionfunc(*args, **kw)It is called, no matter how its parameters are defined.

Summary

Python functions have a flexible parameter form, which can be used for simple calls and very complex parameters.

The default parameter must use an immutable object. If it is a mutable object, a logic error occurs during running!

Pay attention to the syntax for defining variable parameters and keyword parameters:

*argsIs a variable parameter, and args receives a tuple;

**kwIs a keyword parameter, and kw receives a dict.

And how to pass in the Variable Parameter and keyword parameter syntax when calling the function:

Variable parameters can be passed in directly:func(1, 2, 3), You can first assemble list or tuple, and then pass*argsInput:func(*(1, 2, 3));

Keyword parameters can be passed in directly:func(a=1, b=2)Dict can be assembled first, and then**kwInput:func(**{'a': 1, 'b': 2}).

Use*argsAnd**kwIt is a habit of writing Python. Of course other parameter names can also be used, but it is best to use it.

 

Global and local variables

The variables defined in the subroutine are called local variables, and the variables defined at the beginning of the program are called global variables. The global variable scope is the whole program, and the local variable scope is the subroutine that defines the variable. When a global variable has the same name as a local variable, the local variable takes effect in the subroutine that defines the local variable, and the global variable takes effect elsewhere.

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.