Python3 functions
A function is an organized, reusable code segment used to implement a single or related function.
Function can improve the modularity of the application and the reuse rate of the code. You already know that Python provides many built-in functions, such as print(). But you can also create your own functions, which are called user-defined functions.
Define a function
You can define a function with the functions you want, the following are simple rules:
Function code A block begins with the def keyword, followed by the function identifier name and parentheses ().
Any incoming parameters and independent variables must be placed between parentheses, and the spaces between parentheses can be used to define parameters.
The first line of a function can optionally use a documentation string - used to store function descriptions.
The function content starts with a colon and is indented.
return [expression] End the function and optionally return a value to the caller. Return without an expression is equivalent to returning None.
Syntax
Python defines functions using the def keyword, the general format is as follows:
def 函数名(参数列表): 函数体
By default, parameter values and parameter names They are matched in the order defined in the function declaration.
Example
Let us use a function to output "Hello World!":
>>> def hello() : print("Hello World!") >>> hello() Hello World! >>>
For a more complex application, bring parameter variables in the function:
#!/usr/bin/python3 # 计算面积函数 def area(width, height): return width * height def print_welcome(name): print("Welcome", name) print_welcome("php") w = 4 h = 5 print("width =", w, " height =", h, " area =", area(w, h))
Output results of the above examples:
Welcome php width = 4 height = 5 area = 20
Function call
Define a function: give the function a name, specify the parameters contained in the function, and the code block structure.
After the basic structure of this function is completed, you can execute it through another function call or directly from the Python command prompt.
The following example calls the printme() function:
#!/usr/bin/python3 # 定义函数 def printme( str ): "打印任何传入的字符串" print (str); return; # 调用函数 printme("我要调用用户自定义函数!"); printme("再次调用同一函数");
The output result of the above example:
我要调用用户自定义函数! 再次调用同一函数
Pass parameters by value and pass parameters by reference
In Python, all parameters (variables) are passed by reference. If you change the parameters in the function, the original parameters will also be changed in the function that calls this function. For example:
#!/usr/bin/python3 # 可写函数说明 def changeme( mylist ): "修改传入的列表" mylist.append([1,2,3,4]); print ("函数内取值: ", mylist) return # 调用changeme函数 mylist = [10,20,30]; changeme( mylist ); print ("函数外取值: ", mylist)
The object passed into the function and the object to add new content at the end use the same reference. Therefore, the output is as follows:
函数内取值: [10, 20, 30, [1, 2, 3, 4]] 函数外取值: [10, 20, 30, [1, 2, 3, 4]]
Parameters
The following are the formal parameter types that can be used when calling the function:
Required parameters
Keyword parameters
Default parameters
Variable length parameters
Required parameters
Required parameters must be passed into the function in the correct order. The quantity when called must be the same as when declared.
When calling the printme() function, you must pass in a parameter, otherwise a syntax error will occur:
#!/usr/bin/python3 #可写函数说明 def printme( str ): "打印任何传入的字符串" print (str); return; #调用printme函数 printme();
The output result of the above example:
Traceback (most recent call last): File "test.py", line 10, in <module> printme(); TypeError: printme() missing 1 required positional argument: 'str'
Keyword parameters
Keyword parameters are closely related to function calls. Function calls use keyword parameters to determine the passed parameter values.
Using keyword arguments allows the function to be called in a different order than when it was declared, because the Python interpreter can match parameter names with parameter values.
The following examples use parameter names when calling function printme():
#!/usr/bin/python3 #可写函数说明 def printme( str ): "打印任何传入的字符串" print (str); return; #调用printme函数 printme( str = "php中文网");
The output results of the above examples:
php中文网
The following examples demonstrate the use of function parameters and do not need to be used Specify the order:
#!/usr/bin/python3 #可写函数说明 def printinfo( name, age ): "打印任何传入的字符串" print ("名字: ", name); print ("年龄: ", age); return; #调用printinfo函数 printinfo( age=50, name="php" );
Output result of the above example:
名字: php 年龄: 50
Default parameters
When calling a function, if no parameters are passed, the default parameters will be used. In the following examples, if the age parameter is not passed in, the default value is used:
#!/usr/bin/python3 #可写函数说明 def printinfo( name, age = 35 ): "打印任何传入的字符串" print ("名字: ", name); print ("年龄: ", age); return; #调用printinfo函数 printinfo( age=50, name="php" ); print ("------------------------") printinfo( name="php" );
The output result of the above example:
名字: php 年龄: 50 ------------------------ 名字: php 年龄: 35
Indefinite length parameters
You may need a function to handle it More parameters than originally declared. These parameters are called variable-length parameters. Unlike the above two parameters, they will not be named when declared. The basic syntax is as follows:
def functionname([formal_args,] *var_args_tuple ): "函数_文档字符串" function_suite return [expression]
Variable names with an asterisk (*) will store all unnamed variable parameters. If no parameters are specified when the function is called, it is an empty tuple. We can also not pass unnamed variables to the function. The following example:
#!/usr/bin/python3 # 可写函数说明 def printinfo( arg1, *vartuple ): "打印任何传入的参数" print ("输出: ") print (arg1) for var in vartuple: print (var) return; # 调用printinfo 函数 printinfo( 10 ); printinfo( 70, 60, 50 );
The above example output result:
输出: 10 输出: 70 60 50
Anonymous function
python uses lambda to create anonymous functions.
The so-called anonymous means that you no longer use the standard form of def statement to define a function.
lambda is just an expression, and the function body is much simpler than def.
The body of lambda is an expression, not a code block. Only limited logic can be encapsulated in lambda expressions.
The lambda function has its own namespace and cannot access parameters outside its own parameter list or in the global namespace.
Although the lambda function seems to only be able to write one line, it is not equivalent to the inline function of C or C++. The purpose of the latter is to call a small function without occupying stack memory and thereby increasing the execution time. efficiency.
Grammar
The syntax of the lambda function only contains one statement, as follows:
lambda [arg1 [,arg2,.....argn]]:expression
The following example:
#!/usr/bin/python3 # 可写函数说明 sum = lambda arg1, arg2: arg1 + arg2; # 调用sum函数 print ("相加后的值为 : ", sum( 10, 20 )) print ("相加后的值为 : ", sum( 20, 20 ))
The above example output Result:
相加后的值为 : 30 相加后的值为 : 40
return statement
return [expression] statement is used to exit the function and optionally return an expression to the caller. A return statement without parameter values returns None. The previous examples did not demonstrate how to return a value. The following example demonstrates the use of the return statement:
#!/usr/bin/python3 # 可写函数说明 def sum( arg1, arg2 ): # 返回2个参数的和." total = arg1 + arg2 print ("函数内 : ", total) return total; # 调用sum函数 total = sum( 10, 20 ); print ("函数外 : ", total)
The output result of the above example:
函数内 : 30 函数外 : 30
Variable scope
In Python, program variables are not accessible from all locations. Access permissions depend on where the variable is assigned a value.