07 Python function explanation


FunctionA reusable program fragment. They allow you to give a name to a block of code, allow you to run the block of code anywhere in your program with that particular name, and can be repeated any number of times. This is called the calling function.

We have used many built-in functions, such as len and range.

Functions can be defined by the keyword def. This keyword is followed by the identifier name of a function, followed by a pair of parentheses, which can include the names of some variables, and then ends the line with a colon.

The following statement block is part of the function. The following example will show that this is actually very simple:

def say_hello(): 
#The block belongs to this function 
    print('hello world') 
#End of function
say_ Hello () # call function 
say_ Hello () # call the function again


hello world 

How does it work

The way we explained above is called say_ Function of Hello. This function does not use arguments, so there are no variables declared in parentheses. The parameters of the function are just input into the function so that I can pass different values to it and get the corresponding results.

Note that we can call the same function twice, which means we don’t have to write the code again.

Function parameters

Parameters in a function are specified by placing them in a pair of parentheses that define the function, separated by commas. When we call a function, we provide the required value in the same form. Note the terminology used here – the name given when defining a function is called “parameters,” and the value you provide to the function when calling a function is called “arguments.”.

def print_max(a, b): 
    if a > b: 
            Print (a, 'is a relatively large number') 
    elif a == b: 
            Print (a, 'equals', b) 
            Print (B, 'is a relatively large number')
#Direct pass literal 
print_max(3, 4)
x = 5 
y = 7


4 is a relatively large number

How does it work

Here, we name the function print_ Max and use two parameters called a and B, respectively. We use a simple if… Else statement to find the larger number and print it out.

Calling function print for the first time_ Max, we provide this number directly to the function as an argument.

On the second call, we call the function with variables as arguments. print_ Max (x, y) will cause the value of argument x to be assigned to parameter a and the value of argument y to be assigned to parameter B. In both calls, print_ Max works in the same way.

local variable

When you declare variables in the definition of a function, they are not related to variables with the same name outside the function in any way, that is, the variable names only exist in the local part of the function.

This is called the scope of the variable.

The scope of all variables is the block in which they are defined, starting from the definition point where their names are defined.

Case study:

x = 50 
def func(x): 
    Print ('x is: ', x) 
    x = 2 
    Print ('change local variable x to ', x)


X is: 50

How does it work

When we first print out the value named X that exists on the first line of the function blockPython uses the value of this parameter declared in the main code block above the function declaration.

Next, we assign the value 2 to X. X is the local variable of our function. Therefore, when we change the value of X in the function, X in the main code block will not be affected.

With the last print statement, we show the value of X defined in the main block, which confirms that it is not affected by the local variables in the function previously called.

Global statement

If you want to assign a value to a variable at the top of the program (that is, it doesn’t exist in any scope, whether it’s a function or a class), you have to tell python that the variable is not local, but global.

We need a global statement to do this. Because it is impossible to assign a value to a variable defined outside a function without using a global statement.

You can use the values of variables defined outside the function (assuming that there are no variables with the same name in the function). However, this method will not be encouraged and should be avoided, because it is ambiguous for the reader of the program, and it is impossible to find out where the definition of variables is.

By using the global statement, we can clearly see that this variable is defined in the outermost code block.

Case study:

x = 50
def func():
global x
    Print ('x is: ', x)
    x = 2
    Print ('change global variable to ', x)
Print ('x's value is', x)


X is: 50

How does it work

The global statement is used to declare that x is a global variable – so when we assign x to a function, this change affects the value of X that we use in the main block.

You can specify more than one global variable in the same global statement, such as global x, y, Z.

Default parameter values

For some functions, you may want to make some parameters optional and use default values to avoid the situation that users do not want to provide values for them. The default parameter value can effectively help solve this situation.

You can specify default parameter values for parameters by appending an assignment operator (=) to the function definition.


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



How does it work

A function called say prints a string a given number of times. If we do not provide a numeric value, the string will be printed only once by default.We do this by specifying a default value of 1 for the parameter times.

When we use say for the first time, we only provide a string, so the function will print the string only once. When we use say for the second time, we provide both a string and a parameter 5 to declare that we want to say (say) the string five times.

be careful

Only those parameters at the end of the parameter list can be given default parameter values, which means that parameters with default parameter values in the function’s parameter list cannot precede parameters without default parameter values.

This is because the values are assigned in order of where the parameters are. For example, def func (a, B = 5) is valid, but def func (a = 5, b) is invalid.

Keyword parameters

If you have functions that have many parameters and you want to specify only some of them, you can assign values to these parameters by naming them – that’s itKeyword parameters(keyword arguments) – we use naming (keywords) instead of location (the way we’ve always used) to specify parameters in a function

There are two advantages to this

First, we no longer need to consider the order of parameters, and the use of functions will be easier.

Second, we can only assign values to the parameters we want to assign, as long as other parameters have default values.


def func(a, b=5, c=10):
    Print ('a is: ', a,' B is: ', B,' C is: ', c)
func(3, 7)
func(25, c=24)
func(c=50, a=100)


A is: 3 B is: 7 C is: 10

How does it work

The function named func has one parameter with no default parameter value, followed by two parameters with each default parameter value.

When the function is called for the first time, func (3,7), parameter a gets the value 3, parameter B gets the value 7, and C gets the default parameter value 10.

When the function is called the second time, func (25, C = 24), because of its position, variable a gets the value of 25 first. Then, because of the naming – that is, the keyword parameter – Specification, the variable C gets a value of 24. Variable B gets the default parameter value of 5.

When the function is called for the third time, func (C = 50, a = 100), we all use keyword parameters to specify values. Note here that although a is defined before C, we specify the variable C before the variable a.

Variable parameters

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


def total(a=5, *numbers, **phonebook):
    print('a', a)
    #Traverses all items in the tuple
    for num in numbers:
        Print ('num item is: ', Num)
    #Traverse all items in the dictionary
    for key, val in phonebook.items():


a 10

How does it work

When we declare an asterisk parameter such as * param, all positional parameters from here to the end will be collected and aggregated into a tuple called “param”.

Similarly, when we declare a double asterisk parameter such as * * param, all keyword parameters from here to the end will be collected and aggregated into a dictionary named param.

Return statement

The return statement is used to return from a function, which is the interrupt function. We can also choose to return a value from the function when we interrupt it

def maximum(x, y):
    if x > y:
        return x
    elif x == y:
        Return 'two numbers are equal'
        return y
print(maximum(2, 3))



How does it work

The maximum function will return the maximum value in the parameter, in this case the value supplied to the function. It uses a simple set of if… Else statements to find the larger value and return it.

Note that if the return statement does not match any value, it means that it returns none. None is a special type in Python, representing nothing. For example, it is used to indicate that a variable has no value. If it has a value, its value is none.

Each function implies a return none sentence at the end, unless you write your own return statement. You can run print (some)_ Function ()), where some_ The function does not use a return statement, like this:

def some_function(): 

The pass statement in Python is used to indicate a statement block with no content.


There’s a built-in function called Max that already implements the “find maximum” function, so use this built-in function as much as possible.

DocStringsDocument string

Python has a very beautiful function called documentation strings, which is usually called by a shorter name, docstrings.

Docstrings is an important tool that you should use to help you record programs better and make them easier to understand. Amazingly, when the program is actually running, we can even get the document through a function!


def print_max(x, y):
    '"'prints the largest of the two values.
Both numbers should be integers
    #If possible, convert it to an integer type
    x = int(x)
    y = int(y)
    if x > y:
        Print (x, 'bigger')
        Print (y, 'bigger')
print_max(3, 5)


Five is bigger

How does it work

The string in the first logical line of the function is the docstring of the function. Note that the document string is also applicable to the modules and classes mentioned in the related sections

The document string is a string of multiple lines. The first line starts with a capital letter and ends with a period. The second line is empty, followed by a third line that begins with any detailed explanation.

It is strongly recommended that you follow this Convention in all document strings for all your important functions.

We can use thedoc(note the double underline) attribute (the name of the function) to get the function print_ The document string property of max. Just remember that Python treats everything as an object, including functions. We will discuss more details about objects later in the class section.

Automated tools can retrieve documents in your program in this way. Therefore, I strongly recommend that all the important functions you write with document strings. The pydoc command that comes with your Python distribution is similar to the way help () uses document strings.

Nested function

Python allows the creation of nested functions. That is to say, we can define functions in functions, and the existing scope and variable lifetime remain unchanged.

Note: 1. Variables of external functions can be used by internal functions, but cannot be modified by internal functions. To modify, you need to add the keyword nonlocal

def max(a,b):
    return a if a>b else b
print(max(5,2)) #5
def the_max(x,y,z):
    c = max(x,y)
    return max(c,z)
print(the_max(1,5,3))   #5



The function of nested function:

1. Encapsulation – Data Hiding: “nested functions” cannot be accessed externally,

2. Reduce duplicate codes

3. Closure


What is a closure?

If a function is defined in the scope of another function and references the variables of the outer function, the function is called a closure.

Closure is a feature supported by python. It allows functions defined in non global scope to refer to variables in their peripheral space. The variables referenced in these peripheral spaces are called environment variables of the function.

The environment variable and this non global function together form a closure.

def outer():
    a = 1
    def inner():
    return inner
inn = outer()
inn()   #1

Closure features:

The function object returned by a function depends on the variable value inside the function when it is executed. At this time, the actual content returned by the function is as follows:
1 function object
2. External variables and variable values used by function objects

Use inner functions outside functions


We’ve learned a lot about functions, but we haven’t covered all types of functions yet. However, we’ve covered most of the python functions you use every day.

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

07 Python function explanation

Thank you for your attention

Practice address:www.520mg.com/it

Recommended Today

Hot! Front and rear learning routes of GitHub target 144K

Hello, Sifu’s little friend. I’m silent Wang Er. Last week, while appreciating teacher Ruan Yifeng’s science and technology weekly, I found a powerful learning route, which has been marked with 144K on GitHub. It’s very popular. It covers not only the front-end and back-end learning routes, but also the operation and maintenance learning routes. As […]