This article mainly introduces common problems such as creating, calling, and function parameters, and variable scope of Python user-defined functions. For more information, see the organized and reusable functions, code segment used to implement a single, or associated function.
Functions can improve the app's vigilance and reuse of code. You already know that Python provides many built-in functions, such as print (). But you can also create functions by yourself, which are called user-defined functions.
1. define a function
You can define a function that you want to function. The following are simple rules:
1. the Function Code block starts with the def keyword, followed by the function identifier name and parentheses ().
2. any input parameters and independent variables must be placed in the middle of parentheses. Parentheses can be used to define parameters.
3. the first line of the function can selectively use the document string-used to store the function description.
4. the Function content starts with a colon and is indented.
5. Return [expression] ends the function and selectively returns a value to the caller. Return without expression is equivalent to return None.
Syntax
The code is as follows:
Def functionname (parameters ):
"Function _ document string"
Function_suite
Return [expression]
By default, the parameter values and names match in the order defined in the function declaration.
Instance
The following is a simple Python function that uses a string as an input parameter and prints it to a standard display device.
The code is as follows:
Def printme (str ):
"Print the input string to the standard display device"
Print str
Return
II. function call
Defining a function only gives the function a name, specifying the parameters contained in the function and the code block structure. After the basic structure of this function is complete, you can call another function or execute it directly from a Python prompt.
The following example calls the printme () function:
The code is as follows:
#! /Usr/bin/python
# Function definition is here
Def printme (str ):
"Print any input string"
Print str;
Return;
# Now you can call printme function
Printme ("I want to call user-defined functions! ");
Printme ("calling the same function again ");
# Output result of the above instance:
# I want to call user-defined functions!
# Call the same function again
3. pass parameters by value and by reference
All parameters (independent variables) are passed by reference in Python. If you modify parameters in the function, the original parameters are also changed in the function that calls the function. For example:
The code is as follows:
#! /Usr/bin/python
# Writable function description
Def changeme (mylist ):
"Modify input list"
Mylist. append ([1, 2, 3, 4]);
Print "function value:", mylist
Return
# Call the changeme function
Mylist = [10, 20, 30];
Changeme (mylist );
Print "value outside function:", mylist
# The input function uses the same reference as the object that adds new content to the end. The output result is as follows:
# Function value: [10, 20, 30, [1, 2, 3, 4]
# Values outside the function: [10, 20, 30, [1, 2, 3, 4]
IV. function parameters
Python functions can use the following parameter types:
1. required parameters
2. named parameters
3. default parameters
4. variable length parameter
1. required parameters
Required parameters must be input to the function in the correct order. The number of calls must be the same as that of the clear call.
To call the printme () function, you must input a parameter. Otherwise, a syntax error occurs:
The code is as follows:
#! /Usr/bin/python
# Writable function description
Def printme (str ):
"Print any input string"
Print str;
Return;
# Call the printme function
Printme ();
# Output result of the above instance:
# Traceback (most recent call last ):
# File "test. py", line 11, in
# Printme ();
# TypeError: printme () takes exactly 1 argument (0 given)
2. name parameters
The named parameters are closely related to function calls. the caller uses the parameter name to determine the passed parameter values. You can skip parameters that are not passed or pass parameters in disorder, because the Python interpreter can use the parameter name to match the parameter value. Call the printme () function with a named parameter:
The code is as follows:
#! /Usr/bin/python
# Writable function description
Def printme (str ):
"Print any input string"
Print str;
Return;
# Call the printme function
Printme (str = "My string ");
# Output result of the above instance:
# My string
In the following example, the order of naming parameters is not important:
The code is as follows:
#! /Usr/bin/python
# Writable function description
Def printinfo (name, age ):
"Print any input string"
Print "Name:", name;
Print "Age", age;
Return;
# Call the printinfo function
Printinfo (age = 50, name = "miki ");
# Output result of the above instance:
# Name: miki
# Age 50
3. default parameters
When a function is called, if the default parameter value is not passed in, it is considered as the default value. The default age is printed at the next meeting. if the age is not passed in:
The code is as follows:
#! /Usr/bin/python
# Writable function description
Def printinfo (name, age = 35 ):
"Print any input string"
Print "Name:", name;
Print "Age", age;
Return;
# Call the printinfo function
Printinfo (age = 50, name = "miki ");
Printinfo (name = "miki ");
# Output result of the above instance:
# Name: miki
# Age 50
# Name: miki
# Age 35
4. indefinite parameters
You may need a function to process more parameters than when it was originally declared. These parameters are called indefinite parameters. Unlike the preceding two parameters, they are not declared. The basic syntax is as follows:
The code is as follows:
Def functionname ([formal_args,] * var_args_tuple ):
"Function _ document string"
Function_suite
Return [expression]
Variable names with asterisks (*) are used to store all unnamed variable parameters. You can also choose not to pass parameters. Example:
The code is as follows:
#! /Usr/bin/python
# Writable function description
Def printinfo (arg1, * vartuple ):
"Print any input parameters"
Print "output :"
Print arg1
For var in vartuple:
Print var
Return;
# Call the printinfo function
Printinfo (10 );
Printinfo (70, 60, 50 );
# Output result of the above instance:
# Output:
#10
# Output:
#70
#60
#50
5. anonymous functions
Use lambda keywords to create small anonymous functions. This function is named after the standard step for declaring a function with def is omitted.
Lambda functions can receive any number of parameters but can only return the value of one expression, and can only contain commands or multiple expressions.
Anonymous functions cannot directly call print because lambda requires an expression.
A lambda function has its own namespace and cannot access parameters outside its own parameter list or in a global namespace.
Although lambda functions seem to be able to write only one row, they are not equivalent to C or C ++ inline functions. The latter aims to call small functions without occupying the stack memory to increase the running efficiency.
Syntax
The syntax of the lambda function only contains one statement, as follows:
The code is as follows:
Lambda [arg1 [, arg2,... argn]: expression
Example:
The code is as follows:
#! /Usr/bin/python
# Writable function description
Sum = lambda arg1, arg2: arg1 + arg2;
# Call the sum function
Print "Value of total:", sum (10, 20)
Print "Value of total:", sum (20, 20)
# Output result of the above instance:
# Value of total: 30
# Value of total: 40
VI. return statements
Return statement [expression] exits the function and selectively returns an expression to the caller. The return statement without the parameter value returns None. The previous examples do not demonstrate how to return a value. The following example shows how to do this:
The code is as follows:
#! /Usr/bin/python
# Writable function description
Def sum (arg1, arg2 ):
# Returns the sum of the two parameters ."
Total = arg1 + arg2
Print "Inside the function:", total
Return total;
# Call the sum function
Total = sum (10, 20 );
Print "Outside the function:", total
# Output result of the above instance:
# Inside the function: 30
# Outside the function: 30
VII. variable scope
All variables of a program are not accessible anywhere. The access permission determines where the variable is assigned.
The scope of a variable determines which specific variable name you can access in the program. The scopes of the two most basic variables are as follows:
1. global variables
2. local variables
8. variables and local variables
Variables defined in a function have a local scope and global scopes defined outside the function.
Local variables can only be accessed within the declared function, while global variables can be accessed within the entire program. When a function is called, all variable names declared in the function will be added to the scope. Example:
The code is as follows:
#! /Usr/bin/python
Total = 0; # This is global variable.
# Writable function description
Def sum (arg1, arg2 ):
# Returns the sum of the two parameters ."
Total = arg1 + arg2; # total is a local variable here.
Print "Inside the function local total:", total
Return total;
# Call the sum function
Sum (10, 20 );
Print "Outside the function global total:", total
# Output result of the above instance:
# Inside the function local total: 30
# Outside the function global total: 0