Python basis - function

Function (Functions) refers to the program fragment reusable. They allow you give the name for a block of code that allows you to run a block of code anywhere in your application through this special name, and can be repeated any number of times. This is called * Call (Calling) * function. We have already used many built-in functions, such as lenand range.

The concept may function in any complex software (regardless of what programming language) is the most important building blocks, so next we will explore various aspects related functions in this chapter.

By keyword functions can defbe defined. This keyword is followed by an identifier name of a function, and talking to a pair of parentheses, which may include the name of some variables, and then end with a colon, the end of the line. Then came the sentence is part of the function block. The following case will demonstrate this is actually very simple:

Case (save as function1.py):

def say_hello():
    # 该块属于这一函数
    print('hello world')
# 函数结束

say_hello()  # 调用函数
say_hello()  # 再次调用函数

Output:

hello world
hello world

We've explained above define the name say_helloof the function. This function does not use parameters, so there is no declaration of variables in parentheses. Function parameters is enter into function, so that I can pass it to a different value, and the corresponding results obtained.

To note that we can two calls to the same function, which means that we do not have to re-write the code once.

1. Function parameters

Function that can take arguments, the value of the parameter is provided by you, whereby functions can use these values ​​to do something. These parameters are similar to the variables, the values ​​of these variables have been defined when we call the function, and have completed the assignment at run-time function.

Function parameters by placing a pair of parentheses to define the function specified in, and be separated by a comma. When we call the function, we need to provide value in the same form. The terminology used herein is to be noted - the given name referred to the definition of the function * "parameter" (the Parameters) , when calling the function you are referred to the value provided to the function of the "argument" (Arguments) *.

Case (save as function_param.py):

def print_max(a, b):
    if a > b:
        print(a, 'is maximum')
    elif a == b:
        print(a, 'is equal to', b)
    else:
        print(b, 'is maximum')

# 直接传递字面值
print_max(3, 4)

x = 5
y = 7

# 以参数的形式传递变量
print_max(x, y)

Output:

4 is maximum
7 is maximum

Here, we will name the function print_maxand using two parameters are called aand b. We use a simple if...elsestatement to find the greater number, and print it out.

First call print_max, we provide this number to function in a direct form of argument. In the second call, we will be variable as an argument to call the function. print_max(x, y)The argument that the xvalue will be assigned to the parameter a, and the actual parameter yvalues will be assigned to a parameter b. In both calls, the print_maxwork in the same way.

2. Local variables

When you declare a variable in a function definition, they do not in any way other than to live with the same function but with a variable name generation relations, that is, they exist only in the variable name of the function of local (Local) . This is called variable scope (Scope) . Scope all variables block they are defined, starting from the definition of their names defined points.

Case (save as function_local.py):

x = 50

def func(x):
    print('x is', x)
    x = 2
    print('Changed local x to', x)

func(x)
print('x is still', x)

Output:

x is 50
Changed local x to 2
x is still 50

When we first print out the name of the first row present in the function block xwhen the value, Python uses the value of this parameter on the main block of the function declaration statement.

Then, we will value 2assigned to x. xWe are local variables of the function. Thus, when we change the function xvalues when the main code block xwill not be affected.

With the last sentence of the printstatement, we demonstrate the main block of code defined xvalue, thereby confirming that affect local variables of the function it is virtually unaffected by the previous call in.

3. globalStatement

If you want to assign a top-level program variable (that is to say it does not exist in any scope, regardless of function or class), then you must tell the Python variable is not local, but global * (Global) *of. We need to globaldo this in a statement. Because without using globalthe case statement, it is impossible to define a variable outside the function assignment.

You can use the value of the variables defined outside the function (assuming no function variable with the same name). However, this approach will not be encouraged and should be avoided, because it is ambiguous to the reader program, you can not figure out where is the definition of variables. By using the globalstatements of this can be seen clearly in the code block variable is defined in the outermost.

Case (save as function_global.py):

x = 50

def func():
    global x

    print('x is', x)
    x = 2
    print('Changed global x to', x)

func()
print('Value of x is', x)

Output:

x is 50
Changed global x to 2
Value of x is 2

global statement to declare xa global variable ---- Thus, when we function as xwhen the assignment, this change will affect the value of x we used in the main code block.

In the same sentence you can globalspecify more than one global variable statement, for example global x, y, z.

4. The default parameter values

For some functions, you may want to make some parameters optional and use default values, you do not want to avoid the situation provides a value to them. The default parameter values can be effective in helping to resolve this situation. You can attach an assignment operator (a function definition =) to specify the default parameter values for the parameters.

To note that the default parameter value should be constant. More precisely, the default argument value should be immutable ---- This will be explained in more detail in later chapters. For now, just remember on the line.

Case (save as function_default.py):

def say(message, times=1):
    print(message * times)

say('Hello')
say('World', 5)

Output:

Hello
WorldWorldWorldWorldWorld

Named sayfunction for a given number of times in accordance with print string string. If we do not provide a value, then By default, only print one string. We parameter timesdefault value for the specified parameter 1to achieve this.

In the first use say, we only provide a string function and thus will only print a string. In the second use say, we provide both a string, while also providing a parameter 5, declare that we want to * say (Say) * string five times.

Note : Only those parameters at the end of the parameter list can be given default parameter values, which means that the parameters have default parameter values in the parameter list of functions that can not be located no argument before the default parameter values.
This is because the position values are sequentially assigned Parametric located. For example, def func(a, b=5)to be effective, but def func(a=5, b)is not valid.

The keyword arguments

If you have some functions with many parameters and you want only some of which are specified, you can name them to give these parameter assignment - this is the keyword arguments (Keyword the Arguments) - we use the name ( keyword) instead of position (the way we have been used) to specify the parameters function.

This has two advantages ---- First, we no longer need to consider the use of the order parameter, the function will be much easier. Second, we can only those parameters that we want to give to the assignment, as long as the other parameters have default parameter values.

Case (save as function_keyword.py):

def func(a, b=5, c=10):
    print('a is', a, 'and b is', b, 'and c is', c)

func(3, 7)
func(25, c=24)
func(c=50, a=100)

Output:

a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50

Called funcfunction is not a default parameter value of the parameter, followed by two parameters each having a default parameter values.

The first time the function is called func(3, 7), the parameters aobtained values of 3the parameters bobtained value 7, and cwon a default parameter values 10.

When calling the second function, func(25, c=24)due to its position in which the variable aobtained first value 25. Then, as the name that is keyword arguments ---- ---- specified variable cobtained value 24. Variable bget the default parameter values 5.

When calling the function the third time, func(c=50, a=100)we all use keyword parameter to specify the value. Here to note that in spite of athe cpreviously defined, but we are still in a variable abefore the specified variable c.

6. The variable parameters

Sometimes you may want to define a function which can have any number of variables, that is, the number of parameters is variable, which can be achieved by using an asterisk.

Case (save as function_varargs.py) ::

def total(a=5, *numbers, **phonebook):
    print('a', a)

    #遍历元组中的所有项目
    for single_item in numbers:
        print('single_item', single_item)

    #遍历字典中的所有项目
    for first_part, second_part in phonebook.items():
        print(first_part,second_part)

print(total(10,1,2,3,Jack=1123,John=2231,Inge=1560))

Output:

a 10
single_item 1
single_item 2
single_item 3
Inge 1560
John 2231
Jack 1123
None

When we declare such a *paramtime asterisk argument, starting position until all parameters (Positional Arguments) ending will be collected and pooled into one from here called paramtuples (Tuple).

Similarly, when we declare such a **paramtime of double asterisk arguments, all keyword arguments from here until the end will be collected and brought together into a named paramdictionary (Dictionary).

We will in later chapters explore more about tuples and dictionaries.

7. return statement

returnStatement from the function returns , that is, interrupt function. We can also choose to return a value from a function in the interrupt function.

Case (save as function_return.py):

def maximum(x, y):
    if x > y:
        return x
    elif x == y:
        return 'The numbers are equal'
    else:
        return y

print(maximum(2, 3))

Output:

3

maximumFunction will return a maximum value parameter, in the present embodiment is provided to value function. It uses a simple if...elsestatement to find the greater the value and return .

To note that if returnthe statement does not match any of the values it represents a return None. NoneIn Python, a special type, representing nothingness. For example, a variable which is used to indicate no value, if its value is the value None(虚无).

Each function at the end of their sentence implied return None, unless you write your own returnstatement. You can run print(some_function()), in which the some_functionfunction does not use returnstatements like this:

def some_function():
    pass

The Python passstatement indicating a block of statements with no content.

Tip: There is a built-in function called max has been achieved "to find the maximum number of" this feature, so use this built-in function as much as possible.

8. DocStrings

Python has a very beautiful feature called documentation strings (Documentation Strings) , usually using another shorter name when calling it docstrings . DocStrings is an important tool that you should use, it can help you better record the program and make it more easily understood. Amazingly, when the actual program is running, we can even obtain the document through a function!

Case (save as function_docstring.py):

def print_max(x, y):
    '''打印两个数值中的最大数。

    这两个数都应该是整数'''
    # 如果可能,将其转换至整数类型
    x = int(x)
    y = int(y)

    if x > y:
        print(x, 'is maximum')
    else:
        print(y, 'is maximum')

print_max(3, 5)
print(print_max.__doc__)

Output:

5 is maximum
打印两个数值中的最大数。

    这两个数都应该是整数

The first line in the logical line function is the function string document string (docstring) . Documentation string to be noted here is also applicable to the relevant sections of the later-mentioned modules (Modules) and class (Class) .

The document agreed string is a string of multi-line string where the first line with a capital letter, with a period end. The second row is empty, the third line is followed by the start of any detailed explanation. 5 I strongly suggest that you follow this convention in all documentation strings all your important function.

We can use function __doc__(note that one of the double underscores ) attribute (name belonging to the function) function to get the print_maxdocument string property. As long as Python will remember everything as an object, which naturally includes the function. We will be back (Class) class sections discuss more details about the object.

If you've used a Python help()function, then you should already know about the use of the document string. All it does is get the function of the __doc__property and in a neat way to present it to you. You can try the above function only in ---- included in the program help(print_max)on the line. Remember that you can press qto exit button help.

Automated tools can retrieve your application documents in this way. Therefore, I strongly recommend that you write all the important functions for your documents together with string. Python comes with your release pydoccommand help()in a similar manner using the document string.

to sum up

We already know the function of many aspects, but we still have not yet cover all types of functions. However, we've covered most of the day you will use to daily use Python function.

Next, we will learn how to create and use Python modules.

Resources

[1] function · A Byte of Python

Published 66 original articles · won praise 101 · views 30000 +

Guess you like

Origin blog.csdn.net/u010705932/article/details/104405849