Python functions
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.
Define a function
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. Parentheses can be used to define 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
def functionname (parameters): " Function _ Document string " function_suite return [expression]
By default, parameter values and parameter names are matched in the order defined in the function declaration.
Instance
def printme (str): " print an incoming string to a standard display device " Print str return
Function call
Defines a function that gives the function a name, specifies the parameters contained in the function, and the code block structure.
Once the basic structure of this function is complete, you can execute it from another function call or directly from the Python prompt.
The following instance calls the Printme () function:
#!/usr/bin/python#-*-coding:utf-8-*-# definition function def printme (str): "Prints any incoming string" Print str; Return # Call Function Printme ("I want to invoke user-defined function!"); Printme ("Call the same function again");
Execution Result:
I want to invoke the user custom Function! Call the same function again
Parameter passing
In Python, a type belongs to an object, and a variable is of no type:
A=[1,2,3]a= "Runoob"
In the above code, [All-in-one] is a list type,"Runoob" is a string type, and the variable A is no type, she is simply a reference to an object (a pointer), can be a list type object, or can point to a string type Object.
Can change (mutable) and non-changing (immutable) objects
In Python, strings, tuples, and numbers are objects that cannot be changed, and List,dict are objects that can be modified.
immutable Type: variable assignment a=5 and then assign value a=10, here is actually reborn into an int value object 10, then a point to it, and 5 is discarded, not change the value of a, the equivalent of a new student into a.
Variable type: variable assignment la=[1,2,3,4] after assigning a value la[2]=5 is to change the value of the third element of List LA, itself LA is not moving, but its internal part of the value has been modified.
Parameter passing of the Python function:
immutable types: values such as C + + are passed, such as integers, strings, and tuples. such as fun (a), passing only a value, does not affect the A object itself. For example, in Fun (a) to modify the value of a, just modify another copy of the object, does not affect the a itself.
mutable types: references such as C + + are passed, such as lists, dictionaries. such as Fun (LA), is the real transfer of LA, the modified fun outside of LA will also be affected
Everything in Python is an object, strictly meaning we can't say value passing or reference passing, we should say immutable objects and pass mutable objects.
Python-Pass Immutable object instance
#!/usr/bin/python#-*-coding:utf-8-*-def changeint (a): a = ten B = 2ChangeInt (b) Print B # result is 2
The instance has int object 2, the variable that points to it is B, and when passed to the Changeint function, the variable b,a and B both point to the same int object, and at a=10, the new int value Object 10, and a points to it.
Passing a Mutable object instance
#!/usr/bin/python#-*-coding:utf-8-*-# writable function Description def changeme (mylist): "Modify incoming list" mylist.append ([1,2,3,4]); Print "Function inside value:", MyList return # call changeme function mylist = [10,20,30];changeme (mylist);p rint "function outside the value:", MyList
The same reference is used for the object passing in the function in the instance and adding new content at the end, so the output is as follows:
Values in function: [10, 20, 30, [1, 2, 3, 4]] values outside the function: [10, 20, 30, [1, 2, 3, 4]]
Parameters
The following are the formal parameter types that can be used when calling a function:
- Required Parameters
- Keyword parameters
- Default parameters
- Indefinite length parameter
Required Parameters
The required parameters must be passed into the function in the correct order. The number of calls must be the same as when declared.
Call the Printme () function, you must pass in a parameter, or a syntax error will occur:
#!/usr/bin/python#-*-coding:utf-8-*-#可写函数说明def printme (str): "Print any incoming string" Print str; Return #调用printme函数printme ();
Execution Result:
Traceback (most recent): File "test.py", line one, in <module> printme (); Typeerror:printme () takes exactly 1 argument (0 given)
Keyword parameters
Keyword arguments are closely related to function calls, and function calls use keyword parameters to determine the values of the parameters passed in.
Using the keyword argument allows a function call when the order of the arguments is inconsistent with the Declaration, because the Python interpreter can match the parameter values with the name of the argument.
The following instance uses the parameter name when the function Printme () is called:
#!/usr/bin/python#-*-coding:utf-8-*-#可写函数说明def printme (str): "Print any incoming string" Print str; Return #调用printme函数printme (str = "My string");
Execution Result:
My string
The following example shows that the keyword parameter order is not important to show more clearly:
#!/usr/bin/python#-*-coding:utf-8-*-#可写函数说明def printinfo (name, age): "Print any incoming string" Print "name:", name;
print "age", age; Return #调用printinfo函数printinfo (age=50, name= "Miki");
Execution Result:
Name: mikiage 50
Default parameters
When a function is called, the value of the default parameter is considered to be the default value if it is not passed in. The following example prints the default age if age is not passed in:
#!/usr/bin/python#-*-coding:utf-8-*-#可写函数说明def printinfo (name, age = +): "Print any incoming string" Print "name:", name ; Print "Age", age; Return #调用printinfo函数printinfo (age=50, name= "Miki");p Rintinfo (name= "Miki");
Execution Result:
Name: mikiage 50Name: mikiage 35
Indefinite length parameter
You 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:
def functionname ([Formal_args,] *var_args_tuple): "Function _ Document String" function_suite return [expression]
Variable names with an asterisk (*) will hold all unnamed variable arguments. Examples of indeterminate length parameters are as follows
#!/usr/bin/python#-*-coding:utf-8-*-# writable function Description def printinfo (arg1, *vartuple): "Prints any incoming parameter" print "output:" PR int arg1 for var in vartuple: print var return; # call printinfo function Printinfo (70, 60, 50);p Rintinfo
Execution Result:
Output: 10 Output: 706050
anonymous functions
Python uses lambda to create anonymous functions.
- 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.
Grammar
The syntax for a lambda function contains only one statement, as follows:
Lambda [arg1 [, Arg2,..... argn]]:expression
Instance
#!/usr/bin/python#-*-coding:utf-8-*-# writable function Description sum = lambda arg1, arg2:arg1 + arg2; # Call the SUM function print "After adding the value:", SUM (Ten) print "added value is:", SUM (20, 20)
Execution results
The added value is: 30 The added value is: 40
Return statement
Return statement [expression] exits the function, optionally returning an expression to the caller. A return statement without a parameter value returns none. The previous example does not demonstrate how to return a value, and the following example tells you how to do it:
#!/usr/bin/python#-*-coding:utf-8-*-# writable function Description def sum (arg1, arg2): # Returns the sum of 2 parameters. " Total = arg1 + arg2 print "in function:" ; # Call the sum function total = SUM (10, 20);
Execution Result:
Inside function: 30
Variable scope
All variables of a program are not accessible in any location. Access permissions depend on where the variable is assigned.
The scope of the variable determines which part of the program you can access which particular variable name. The two most basic variables are scoped as follows:
- Global variables
- Local variables
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:
#!/usr/bin/python#-*-coding:utf-8-*-total = 0; # This is a global variable # writable function description def sum (arg1, arg2): #返回2个参数的和. " Total = Arg1 + arg2; # Total is a local variable here. The print function is a local variable: #调用sum函数sum (+);p rint "function is a global variable:", total
Execution Result:
Inside a function is a local variable: 30 is a global variable outside the function: 0
15. Python function