1, What is a function?
A function is a self-contained unit of program code used to complete a specific task. In object-oriented programming classes, functions are often called methods. Different functions play different roles in the program, play different roles and perform different actions. For example, the print() function can print the object to the screen; Some other functions can return a value for the program to use. For example, len() returns the number of elements of the object with computable length to the program.
2, Why use functions?
First, the use of functions can reuse code, save the writing of repetitive code, and improve the reuse rate of code. If a specific function needs to be used multiple times in the program, you only need to write an appropriate function. The program can call the function wherever necessary, and the same function can be invoked in different programs, just like the print() and input() functions we often use.
Second, the function can encapsulate the internal implementation, protect the internal data and achieve transparency to users. Many times, we regard functions as "black boxes", that is, corresponding to a certain input, they will produce a specific result or return an object. Often, the user of the function is not the function writer. The user of the function does not need to consider the internal behavior of the black box. He can put his energy into the design of his own business logic rather than the implementation details of the function. Only the function designer or writer needs to consider the details of the internal implementation of the function, how to expose the external interface and what data to return, that is, the design of the API.
Third, even if a function is used only once in the program, it is necessary to implement it in the form of function, because the function makes the program modular, from "a mass of loose sand" to "a neat team", which is conducive to the reading, calling, modification and improvement of the program. For example, suppose you are writing a program that implements the following functions:
def read_numbers(): """ Read in a line of numbers :return: """ pass def sort_numbers(lis): """ Sort numbers :return: """ pass def avg_numbers(lis): """ Average the numbers :return: """ pass def show_number(lis): """ Print histogram :return: """ pass if __name__ == '__main__': number_list = read_numbers() sort_numbers(number_list) avg_numbers(number_list) show_number(number_list)
Of course, four of these functions are read_numbers(),sort_numbers(),avg_numbers() and show_ The implementation details of numbers () need to be written by yourself. The descriptive function name can clearly indicate the function and organizational structure of the function, and then each function can be designed independently until the required function is completed. If these functions are sufficiently generalized, they can also be called in other programs.
3, Define function:
def Function name(parameter): # Internal code return expression
For example:
def summer(lis): """ Here is the function description document, doc Location of :param lis: Description of the parameter list :return: Description of the return value """ total = 0 for i in lis: total += i return total
In the process of defining functions, you should pay attention to the following points:
-The function code block begins with the def keyword, followed by a space followed by the function identifier name and parentheses (), followed by a colon.
- Any parameters passed in must be placed between parentheses.
- After the first line of the function statement, you can optionally use the document string - used to store the function description.
- The function content starts with a colon and is indented.
- Use return to end the function. None is returned by default.
- The return statement is still inside the function body and cannot be retracted. Until all the code of the function is written, it does not retreat and indent, indicating the end of the function body.
4, How to call a function?
Function is written to be called. To call a function, you must use the function name followed by parentheses to call the function. At the same time of calling, the corresponding number and type of parameters shall be provided according to the function definition body, and each parameter shall be separated by commas. Due to the characteristics of dynamic language, Python does not check the parameter type during syntax and lexical analysis, but during execution, if the parameter type does not comply with the internal operation mechanism of the function, corresponding errors will pop up, such as:
>>> all(0, -1, 3) Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> all(0, -1, 3) TypeError: all() takes exactly one argument (3 given) >>> all([0, -1, 3]) False
Python's built-in function all() requires one parameter, but we gave three at the beginning. Later, we will provide the three parameters as a whole list, so there is no problem.
1.return statement:
The return statement is used to indicate the end of the function execution and return the object after return. Sometimes, the function does not need to return any value. At this time, it does not need a return statement. It returns None by default in the background without any prompt. But more often we still need to return something. Once a return statement is encountered during function execution, all code in the function body will be ignored and directly jump out of the function body. Even if you're in a cycle now.
def func(): pass return # At this point, the following code can never be executed. # But from the grammatical and lexical levels, there are no mistakes. print(1) abs(-1) pass
2. What can return?
- Don't return anything, just return: return
- Number / string / any data type: return 'hello'
- An expression: return 1+2
- A judgment statement: return 100 > 99
- A variable: return a
- A function call: return func()
- Multiple return values separated by commas: return a, 1+2, "hello"
In short, the function can return almost any Python object.
3. How to receive the return value of a function?
When we call a function, we can save the return value of the function in a variable.
def func(): pass return "something" result = func()
For functions that return multiple values at the same time, you need to receive a corresponding number of variables separated by commas:
def func(): return 1, [2, 3], "haha" a, b, c = func()
4. Parameter transfer
Functions usually have parameters, which are used to transfer external actual data into the function for processing. However, in dealing with the problem
Different situations occur when parameters of the same data type are. All this is because of the following two points.
-Python's function parameters pass the memory address of the actual object.
-Python's data types are divided into variable data types and immutable data types.
Look at the following example
a = 1 def func(a): print("Before modifying inside a function,variable a The memory address of is: %s" % id(a)) a = 2 print("After modification inside the function,variable a The memory address of is: %s" % id(a)) print("Function internal a Is: %s" % a) print("Before calling a function,variable a The memory address of is: %s" % id(a)) func(a) print("Function external a Is:%s" % a)
The print result is:
Before calling a function,variable a The memory address of is 1401140288 Before modifying inside a function,variable a The memory address of is 1401140288 After modification inside the function,variable a The memory address of is 1401140320 Function internal a Is: 2 Function external a Is: 1
Why is the memory address of a inside and outside the function different when a = 2? That is, after that, a inside and outside the function is two different objects.
Many times, we are confused by this kind of similar problem because of the improper naming of function parameters. If we change the above parameter name to b, it may be much easier to understand (pay attention to the changes in the text). The execution result is the same.
a = 1 def func(b): print("Before modifying inside a function,variable b The memory address of is: %s" % id(b)) b = 2 print("After modification inside the function,variable b The memory address of is: %s" % id(b)) print("Function internal b Is: %s" % b) print("Before calling a function,variable a The memory address of is: %s" % id(a)) func(a) print("Function external a Is:%s" % a)
What I just said is immutable type parameters. What if they are variable types, such as lists?
a = [1, 2, 3] def func(b): print("Before modifying inside a function,variable b The memory address of is: %s" % id(b)) b.append(4) print("After modification inside the function,variable b The memory address of is: %s" % id(b)) print("Function internal b Is: %s" % b) print("Before calling a function,variable a The memory address of is: %s" % id(a)) func(a) print("Function external a Is:%s" % a)
The results are:
Before calling a function,variable a The memory address of is 34875720 Before modifying inside a function,variable b The memory address of is 34875720 After modification inside the function,variable b The memory address of is 34875720 Function internal b Is: [1, 2, 3, 4] Function external a Is:[1, 2, 3, 4]
When calling the function, the address of the list object a is passed to the variable B inside the function. b. When append (4), find the list object [1,2,3] according to the memory address passed in, and add 4 after it.
It can be seen that a and b actually point to the same object. Why is that? Because the most critical code of b.append(4), which is different from the "=" assignment statement, will not create new variables. As a variable type, the list has an append method, which is just a call to the list. Therefore, a and b are actually the same object.
5, Parameter type
Most functions receive a certain number of parameters, and then output different results according to the values of the parameters provided during the actual call. As we said earlier, it is a bad habit to define the internal parameter name of a function as the name of an external variable. It is easy to confuse thinking and even make mistakes. Generally, we define and pass parameters to functions as follows:
x, y, z = 1, 2, 3 def add(a, b, c): return a+b+c add(x, y, x) # Use variables to pass parameters add(4, 5, 6) # It is also possible to pass values directly.
In the above example, a, b and c are called formal parameters, or formal parameters for short. x, y, z and 4, 5 and 6 are called actual parameters, which are called actual parameters for short, that is, the actual values to be passed. The parameters we usually discuss refer to formal parameters.
When defining a function, the name and location of the parameters are determined, and the interface of the function is fixed. For the caller of a function, it is enough to know how to pass the correct parameters and what value the function will return. The complex logic inside the function is encapsulated and the caller does not need to know. The parameter definition of Python functions is very flexible. In addition to the normally defined location parameters, you can also use default parameters, dynamic parameters and keyword parameters, which are the types of formal parameters.
1. Position parameters
It is also called mandatory parameters. Sequence parameters are the most important and must be explicitly provided when calling functions! The position parameters must correspond to each other one by one in order, and they can be passed in a small number!
A, b and c in the above example are location parameters. When we call with add(4, 5, 6), we pass 4 to a, 5 to b and 6 to c one-to-one. Calls such as add(4, 5, 6, 7), add(4) and add(5, 4, 6) are wrong. Among them, the call of add(5, 4, 6) has no syntax problem, but the output result may be inconsistent with the expectation.
Note: Python does not check the data type when passing function parameters. Theoretically, you can pass any type!
def add(a, b, c): return a+b+c result = add("haha", 2, 3)
However, in the above add function, if you pass a string and two numbers, the result is an exception, because the string cannot be added to the number. This is the characteristic of Python's weak data type and dynamic language. When it is simple and convenient, you need to implement data type checking yourself.
2. Default parameters
When defining a function, if you provide a default value for a parameter, the parameter becomes the default parameter and is no longer a positional parameter. When calling a function, we can pass a custom value to the default parameter or use the default value.
def power(x, n = 2): return x**n ret1 = power(10) # Use the default parameter value n=2 ret2 = power(10, 4) # Pass 4 to n and actually calculate the value of 10 * * 4
n in the above example is the default parameter. Default parameters can simplify function calls. While providing simple calls for the most commonly used cases, they can also pass new values in special cases. However, there are several points to note when setting default parameters:
- The default parameter must be after the position parameter!
If you violate this point, you can't pass it directly at the grammatical level.
# This is a wrong example def power(n = 2,x): return x**n
- When there are multiple default parameters, the more commonly used ones are usually put in the front and the less changed ones are put in the back.
def student(name, sex, age, classroom="101", tel="88880000", address="..."): pass
- When calling a function, try to provide the default parameter name for the actual parameters.
def student(name, sex, age, classroom="101", tel="88880000", address="..."): pass student('jack','male',17) # All others use default values student('tom','male',18,'102','666666','beijing') # All specifies the value of the default parameter student('mary','female',18,'102',tel='666666') # Pick it student('mary','female',18,tel='666666','beijing') # This is the wrong way to pass parameters student("mary","female",18,tel="666666",address="beijing")
Note the last two calling methods. The penultimate one is wrong and the last one is correct. Why is that? Because all actual parameters that do not provide parameter names will be matched sequentially from the left to the right of the parameter list as position parameters!
- Pass parameters using parameter names
Usually, when we call a function, the location parameters are passed in order, and must be in front of the default parameters. However, if you specify the parameter name of the location parameter to the argument when passing the location parameter, the location parameter can also be called out of order, for example:
def student(name, age, classroom, tel, address="..."): pass student(classroom=101, name="Jack", tel=66666666, age=20)
Note that the specified parameter name must be the same as the location parameter name.
- The default parameter should point to the same object as possible!
Here is a real Python interview question:
def func(a=[]): a.append("A") return a print(func()) print(func()) print(func())
Don't test on the computer. Just rely on the code. Can you tell the printed results?
Because when the Python function body is read into memory, the empty list object pointed to by the default parameter a will be created and placed in memory. Because the default parameter a itself is also a variable, it saves the address pointing to the object []. Each time the function is called, an A is added to the list pointed to by A. A does not change. It always saves the address pointing to the list and changes the data in the list! We can test:
def func(a=[]): print("Function inside a Your address is:%s" % id(a)) a.append("A") return a b = func() print('here b The value of is:%s' % b) print("Function external b Your address is:%s" % id(b)) print("-------------") c = func() print('here c The value of is:%s' % c) print("Function external c Your address is:%s" % id(c)) print("-------------") d = func() print('here d The value of is:%s' % d) print("Function external d Your address is:%s" % id(d))
The print result is:
Function inside a The address of is 39287880 here b The value of is:['A'] Function external b The address of is 39287880 ------------- Function inside a The address of is 39287880 here c The value of is:['A', 'A'] Function external c The address of is 39287880 ------------- Function inside a The address of is 39287880 here d The value of is:['A', 'A', 'A'] Function external d The address of is 39287880
So how to avoid this problem?
Use immutable data type as default!
def func(a=None): # Note the following if statement if a is None: a = [] a.append("A") return a print(func()) print(func()) print(func())
Set the default parameter A to an immutable object such as None, number or string. Inside the function, convert it to A variable type, such as an empty list. In this way, no matter how many times it is called, the run result will be ['A '].