Function
Functions are well-organized, reusable pieces of code that are used to implement a single, or associated function.
Functions can improve the modularity of the application, and the reuse of the code.
1. Defining functions
The Python definition function uses the DEF keyword, and the general format is as follows:
def 函数名(参数列表): 函数体
A simple explanation:
- The function code block begins with a def keyword followed by the function identifier name and parentheses ().
- Any incoming parameters and arguments must be placed in the middle of the parentheses, and the parentheses can be used to define the parameters.
- The first line of the function statement can optionally use the document string-for storing the function description.
- The function contents begin with a colon and are indented.
- return [expression] ends the function, optionally returning a value to the caller. If you do not write Retuen, no return is indicated.
Returns multiple values:
You can return multiple values with return, which are automatically packaged as a tuple when returned. You can also directly use multiple variables to receive these return values when calling a function.
Function call:
Define a function: Give the function a name, specify the parameters contained in the function, and the code block structure.
Once the basic structure of this function is complete, you can execute it through another function call or directly from the Python command prompt.
Lifting chestnuts:
# 计算面积函数def area(width, height): return width * heightdef print_welcome(name): print("Welcome", name)print_welcome("KKKK")w = 4h = 5print("width =", w, " height =", h, " area =", area(w, h))
Run:
2. function parameters 1. Position parameters
Write a function to calculate X2:
def power(x): return x * x
For the Power (x) function, the parameter x is a positional parameter. When we call the power function, we must pass in the only one parameter X
def power(x, n): s = 1 while n > 0: n = n - 1 s = s * x return s
Change the function above to a function that computes n, and the modified power (x, N) function has two parameters: X and N, both of which are positional parameters, and when the function is called, the two values passed in the order of position are assigned to the parameters x and n sequentially.
2. Default parameters
Format: Parameter name = default value
When we call the function, we do not want to enter so many parameters, then we define the function when we set the default parameters.
If a parameter is not passed to the default parameter, the default value of the default parameter is used.
def power(x, n=2): s = 1 while n > 0: n = n - 1 s = s * x return s
Thus, when we call Power (5), which is equivalent to calling power (5, 2) and calling Power (5,4), the default value of 2 does not take effect because the value is passed to the default parameter. That's what the default parameter does.
3. Variable parameters
Format: * Parameter name
As the name implies, the variable parameter is the number of parameters passed in is variable, can be one, 2 to any, or 0.
Inside a function, a tuple is received, that is, multiple values passed through a mutable parameter are stored in tuples.
Lifting chestnuts:
def printinfo( arg1, *vartuple ): "打印任何传入的参数" print ("输出: ") print (arg1) print (vartuple)# 调用printinfo 函数printinfo( 70, 60, 50 )
Run:
If you already have a list or tuple, you can call a mutable parameter before the list or tuple variable name adds a *
Lifting chestnuts:
def printinfo(arg1, *vartuple): "打印任何传入的参数" print("输出: ") print(arg1) print(vartuple)tuple = (60,50,40)# 调用printinfo 函数printinfo(70,*tuple)
Run:
4. Keyword parameters
Format: * * Parameter name
Variable parameters allow you to pass in 0 or any of the parameters that are automatically assembled as a tuple when the function is called. The keyword parameter allows you to pass in 0 or any parameter with parameter names that are automatically assembled inside the function as a dict.
def person(name, age, **kw): print(‘name:‘, name, ‘age:‘, age, ‘other:‘, kw)person(‘ttt‘,22)
function person In addition to the required parameter name and age, there is a keyword parameter, kw. When you call this function, you can pass in only the required parameters:
You can also pass in any number of keyword parameters:
Similar to mutable parameters, you can also pass a key-value pair into a function by using a keyword argument, by adding two dict to the name of the dictionary variable before the call.
def person(name, age, **kw): print(‘name:‘, name, ‘age:‘, age, ‘other:‘, kw)dict1 = {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘}person(‘ttt‘,22,**dict1)
Run:
Keyword parameter effect:
The function of the extension function. For example, in the person function, we are guaranteed to receive both the name and the age parameters, but we can receive them if the caller is willing to provide more arguments. Imagine you are doing a user registration function, in addition to the user name and age is required, the other is optional, using the keyword parameters to define this function can meet the requirements of registration.
Named keyword parameters
For the keyword argument, the caller of the function can pass in any unrestricted keyword argument. As to exactly what is passed in, it needs to be checked inside the function via KW.
Still taking the person () function as an example, we want to check if there are city and job parameters:
def person(name, age, **kw): if ‘city‘ in kw: # 有city参数 pass if ‘job‘ in kw: # 有job参数 pass print(‘name:‘, name, ‘age:‘, age, ‘other:‘, kw)
However, the caller can still pass in the Unrestricted keyword parameter:
person(‘Jack‘, 24, city=‘Beijing‘, addr=‘Chaoyang‘, zipcode=123456)
If you want to restrict the name of the keyword argument, you can use the named keyword argument, for example, to receive only city and job as the keyword parameter. The functions defined in this way are as follows:
def person(name, age, *, city, job): print(name, age, city, job)
Unlike the keyword parameter *kw, the named keyword parameter requires a special delimiter , and the following parameters are treated as named keyword parameters.
The method is called as follows:
person(‘Jack‘, 24, city=‘Beijing‘, job=‘Engineer‘)
If there is already a mutable parameter in the function definition, then the named keyword argument will no longer need a special delimiter *:
def person(name, age, *args, city, job): print(name, age, args, city, job)
The named keyword argument must pass in the parameter name, which differs from the positional parameter. If the parameter name is not passed in, the call will error.
A named keyword parameter can have a default value, which simplifies the invocation:
def person(name, age, *, city=‘Beijing‘, job): print(name, age, city, job)
Because the named keyword parameter city has a default value, the city parameter is not passed in when called:
person(‘Jack‘, 24, job=‘Engineer‘)
When using named keyword parameters, it is important to note that if there are no mutable parameters, you must add one as a special delimiter. If missing , the Python interpreter will not recognize the positional parameter and the named keyword parameter:
def person(name, age, city, job): # 缺少 *,city和job被视为位置参数 pass
3. Combination parameters
Define functions in Python, which can be combined using positional parameters, default parameters, variable parameters, keyword parameters (named keyword arguments). However, the order in which the parameters are defined must be: positional, default, mutable, keyword (named keyword parameter).
def f1(a, b, c=0, *args, **kw): print(‘a =‘, a, ‘b =‘, b, ‘c =‘, c, ‘args =‘, args, ‘kw =‘, kw)def f2(a, b, c=0, *, d, **kw): print(‘a =‘, a, ‘b =‘, b, ‘c =‘, c, ‘d =‘, d, ‘kw =‘, kw)f1(1, 2)f1(1, 2, c=3)f1(1, 2, 3, ‘a‘, ‘b‘)f1(1, 2, 3, ‘a‘, ‘b‘, x=99)f2(1, 2, d=99, ext=None)
Run:
4. Global variables and local variables
Variables defined inside a function have a local scope, which defines the owning global scope outside of the function.
Local variables can only be accessed within their declared functions, while global variables are accessible throughout the program. When a function is called, all variable names declared within the function are added to the scope. The following example:
total = 0 # 这是一个全局变量# 可写函数说明def sum( arg1, arg2 ): #返回2个参数的和." total = arg1 + arg2 # total在这里是局部变量. print ("函数内是局部变量 : ", total) return total#调用sum函数sum( 10, 20 )print ("函数外是全局变量 : ", total)
The result of the above example output:
函数内是局部变量 : 30函数外是全局变量 : 0
Global keyword
Declare the variable as a global variable.
Small chestnuts:
num = 1def fun1(): num = 123 print(num)fun1()print(num)
The result of the instance output:
1231
The following instance modifies the global variable num:
num = 1def fun1(): global num #使用 global 关键字声明 num 为全局变量 print(num) #现在num已经是全局变量了 num = 123 #改变全局变量num的值 print(num)fun1()print(num)
The result of the above example output:
1123123
Python Learning-functions