The strongest Python 3 Foundation
What is a function? A function is a piece of code that can be reused by another program, that is, these codes are common in some cases, which means that the input and output formats in the function are the same.
Before that, we have used many functions in the system, such as the print() function used every time, and the list's built-in function append(), insert(). These are built-in functions in the system. We don't need to care about the code details, just know how to use them. Now the question is, if we want to create a reusable function ourselves, how do we create it?
introduce
Let's take a look at the basic format of the function. Python has strict requirements on the code format and can't run as long as there is a little format error, so we must pay attention to the warning given to us by the text editor and correct the format in time.
As can be seen from the above figure, the definition of a function can be divided into five parts: def keyword, function name, parameters, function body and the content returned by the return keyword. The following example can be used to simplify the contents of the diagram. Note: before each different part of the function, you must indent a part with four spaces. You can see the following example. In the example, four spaces are deliberately empty in front of the function body to distinguish this part from the function body.
def Function name(parameter list): Function body
What happens if you don't use four spaces to distinguish? Unlike Java, python does not have a clear code range. For example, Java uses braces to enclose the function body, while Python advocates simplicity, so the braces that specify the function range are removed. Therefore, if you do not use spaces to clearly distinguish the function body, it will not be recognized. You can see the difference between Java and python function examples below.
# Java version function public int sum(int x, int y) { if (x > y) { return x + y; } else { return x; } } # ===================================================================== # Java version nonstandard code public int sum(int x, int y) { if (x > y) { return x + y; } else { return x; } } # ===================================================================== # Python version function def sum(x, y): if x > y: return x + y else : return x
You can see that the Java version functions in the above example obviously have many more braces and brackets than python. We don't need to understand the meaning of public in Java, just look at the format. In Python, because there is no special function boundary, only four spaces can be used to divide the boundary of each part, while Java uses curly braces and parentheses to standardize the boundary, so even if the code is not standardized in the second example, there will be no error. At most, the cost of identification is high. If Python doesn't write code in a standard way, it will directly report an error, reminding us to add a space in front of each part.
Here are two practical examples. In the following example, two functions are defined. Each function returns a string, and then the two results are spliced when calling the function externally. Therefore, the final output result is the result of the splicing of the two strings.
def hello(): return 'Hello World! ' def python(): return 'Python' print(hello() + python()) # Output > > > Hello World! Python
The function in the example here only defines a function body for printing a string, which will be printed when calling the function below.
def myPrint(): print('Hello World!') myPrint() # Output > > > Hello World!
1, Parameters
There are four types of function parameters: required parameter, keyword parameter, default parameter and indefinite length parameter.
Parameter name | format | explain |
---|---|---|
Required parameters | def func(param1, param2) | Required parameters must be passed in the correct order. |
Keyword parameters | def func(pa=param1, param2) | Parameters can be matched according to the parameter name without passing them in order |
Default parameters | def func(param1, param2=123) | If no parameter is given, you can specify a parameter with a default value |
Indefinite length parameter | def func(param1, *param2) | If the actual number of parameters passed in cannot match the expected number of parameters, the variable length parameter can be used |
1. Required parameters
Mandatory parameters are parameters that must be passed in and must be passed in the correct order. If they are not passed in or in the correct order, the function will not work normally. You can see the following examples.
The following example is that the parameters are passed in the correct order, so the results can be output correctly in the end.
def func(param1, param2): print(param1, '-', param2) func('str', 123) # Output > > > str - 123
And the following two examples, One is missing parameters (Python will report an error), and the other is not passed in the correct order (different from the actual expected results). Neither of the two examples can correctly complete the process required by the function. When the function without parameters is executed, the console will output the error of the corresponding missing parameters. In the second example, the output results are different from what we think because the parameters are not passed in the specified order.
# Missing parameter def func(param1, param2): print(param1, '-', param2) func('str') # Output > > > TypeError: func() missing 1 required positional argument: 'param2' # =========================================================================================== # Parameters are not passed in the correct order def func2(str, num): print('String parameters:', str) print('Digital parameters:', num) func2(123, 'Python') # Output > > > String parameters: 123 Digital parameters: Python
2. Keyword parameters
Keyword parameters are passed in the same way as format formatted parameters. They are passed in the form of key value pairs to specify that a value corresponds to a specific key, and then the corresponding value will be obtained according to the key in the function. When there are many parameters, this keyword parameter can quickly identify the parameters we want.
At the same time, keyword parameters can be passed in according to the established order instead of the required parameters, that is, as long as the specified key value pairs are correct, the order will not affect the output when they are passed in.
We still use an example to show the keyword parameters, and pass in the parameters in a different order than the parameters specified by the function. We can see that the output in the example is in line with what we think.
def func(str, num): print('String parameters:', str) print('Digital parameters:', num) func(num = 123, str = 'Python') # Output > > > String parameters: Python Digital parameters: 123
If the parameter is passed in as a keyword parameter at the beginning, then all parameter assignments can only be passed in as a keyword, and can no longer be passed in as a required parameter, because this will lead to ambiguity.
def func(str, num): print('String parameters:', str) print('Digital parameters:', num) func(123, str = 'Python') # Output > > > TypeError: func() got multiple values for argument 'str'
3. Default parameters
Compared with the above two methods of passing in parameters, when actually calling a function, the default parameter does not have to pass in a value to the parameter corresponding to the specified default value, because if the value is not passed in for the parameter with the specified default value, Python can also know that the parameters that are not passed in can continue with the specified default value.
def func(str, num=123): print('String parameters:', str) print('Digital parameters:', num) func('Python') # Output > > > String parameters: Python Digital parameters: 123
4. Variable length parameters
Variable length parameters are parameters with asterisks to represent param, which means that there can be one or more parameters passed in, or no parameters passed in, and the type of parameters passed in is not limited. Finally, if printed in the function, it can be found that the variable length parameter is finally a tuple type data.
def func(str, *args): print('String parameters:', str) print('Variable length parameters:', args) func('Python', 456, 89.3, 'Java') # Output > > > String parameters: Python Variable length parameters: (456, 89.3, 'Java') # ================================================================ def func2(str, *args): print('String parameters:', str) print('Variable length parameters:', args) func2('Python') # Output > > > String parameters: Python Variable length parameters: ()
As mentioned here, the variable length parameter is marked with an asterisk. In fact, Python has a parameter with two asterisks. The parameter with two asterisks can receive multiple keyword parameters. The two functions can be used together, but the order of use is specified. The variable length parameter must be in front of the parameter with two asterisks.
def func(str, *args, **param): print('String parameters:', str) print('Variable length parameters:', args) print('Dictionary type parameters:', param) func('Python', 456, 89.3, 'Java', a = 1, b = 2, c = 3) # Output > > > String parameters: Python Variable length parameters: (456, 89.3, 'Java') Dictionary type parameters: {'a': 1, 'b': 2, 'c': 3}
You can see that in the above example, the dictionary type is finally converted into the function by passing in multiple keyword parameters.
2, Anonymous function
Python uses lambda to create anonymous functions. Anonymous functions can only be used in limited cases, because anonymous functions can only be a single expression and cannot contain code blocks like ordinary functions. Let's take a look at the comparison between anonymous functions and ordinary functions.
# Ordinary function def sum(a, b): return a + b print(sum(1, 2)) # Output > > > 3 # Anonymous function sum = lambda a, b: a+b print(sum(1, 2)) # Output > > > 3
From the above two examples, the calling method of anonymous functions is actually the same as that of ordinary functions. At the same time, we can see that the format of lambda is actually very simple, which is divided into three parts: lambda keywords, parameters and expressions. You can't add a large number of code blocks to the expression, so you can only add limited logic when using it.
lambda [arg1 [,arg2,.....argn]]:expression
summary
This part mainly introduces the basic definition of function and the types of various parameters of function. Parameters can be mixed in function, and it is not necessarily required to be specific. The definition of a function is relatively simple. It is important to pay attention to the format of the code in the function in Python. You can't write every line on the far left, because Python has a very strict format check. If the format is different, the results may be different.