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. You already know that Python provides a number of built-in functions, such as print (). But you can also create your own functions, which are called user-defined functions.
You can define a function that you want to function, and here are the simple rules:
- 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. Return without an expression is equivalent to returning None.
- Grammar
The Python definition function uses the DEF keyword, and the general format is as follows:
-
1 def function name (argument list): 2 function body
By default, parameter values and parameter names are matched in the order defined in the function declaration. For example: Let's use a function to output "Hello world! ":
-
1 def hello (): 2 print ( hello world! " ) 3 4 Hello () # call function 5 6 Hello world! # The result of the call function
Applications with more complex points, with parametric variables in the function: Calculates a function that multiplies two numbers:
-
1 def calc (b): # a,b is formal parameter, formal argument 2 Span style= "COLOR: #008000" ># positional parameters, also called required parameters, will not be filled in error 3 res=a*b 4 print ( ' %s *%s =%s "% (a,b,res)) 5 calc (7,9) # 7 and 8 are arguments, actual parameters 6 7 # 7 * 9 = 63 result of calling function
default parameter
- When a function is called, default parameters are used if no arguments are passed. The default value is used if the age parameter is not passed in the following instance:
1 defPrintinfo (name, age = 35 ):2 "print any passed-in string"3 Print("Name:", name)4 Print("Age:", age)5 return6 #Call the Printinfo function7Printinfo (age=50, name="Runoob" )8 Print("------------------------")9Printinfo (name="Runoob" )Ten One #The result of the above example output: A Name: Runoob -Age: 50 ------------------------- the Name: Runoob -Age: 35Indefinite length parameterYou may need a function that can handle more arguments than was originally declared. These parameters are called indeterminate length parameters, and are not named when declared, unlike the above 2 parameters. The basic syntax is as follows:
1 def functionname ([Formal_args,] *var_args_tuple):2 " Function _ document string " 3 function_suite 4 return [Expression]
Variable names with an asterisk (*) will hold all unnamed variable arguments. If a parameter is not specified when the function is called, it is an empty tuple. We can also not pass unnamed variables to the function. The following example:
#Writable Function DescriptiondefPrintinfo (arg1, *vartuple):"Print any parameters passed in" Print("Output:") Print(arg1) forVarinchvartuple:Print(Var)return #Call the Printinfo functionPrintinfo (10) Printinfo (70, 60, 50) The above example output: output:10Output:706050anonymous functionsPython uses lambda to create anonymous functions.
Anonymity means that a function is no longer defined in a standard form such as a DEF statement.
- Lambda is just an expression, and the function body is much simpler than def.
- The body of a lambda is an expression, not a block of code. Only a finite amount of logic can be encapsulated in a lambda expression.
- The lambda function has its own namespace and cannot access parameters outside its own argument list or in the global namespace.
- Although the lambda function appears to be only a single line, it is not equivalent to a C or C + + inline function, which is designed to call small functions without consuming stack memory to increase operational efficiency.
The syntax for a lambda function contains only one statement, as follows:
1 Lambda # after the colon is the function body, is also the function of the processing logic, the colon is preceded by the return value 2 Print (P (2)) 3 4 # The result is 5 3
Global variables and local variablesVariables 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 variables defined inside the function are local variables, which are used only within the function and cannot be called out of the function. The following example:
1Total = 0#This is a global variable2 3 defsum (arg1, arg2):4 #returns the and of the 2 parameters.5Total = Arg1 + arg2#Total Here is the local variable.6 Print("inside a function is a local variable:", total)7 return Total8 9 #Call the SUM functionTenSUM (10, 20 ) One Print("outside the function is a global variable:", total) A - #The result of the above example output: - theInside the function is a local variable: 30 -Outside the function is a global variable: 0