Python Custom function creation, invocation, and function parameters detailed _python

Source: Internet
Author: User
Tags anonymous function definition in python

A function is a piece of code that is organized, reusable, and used to implement a single, or associated, function.
Functions can improve the modularity of applications and the reuse of code. You already know that Python provides a number of built-in functions, such as print (). But you can also make your own creative functions, which are called user-defined functions.
One, define a function
You can define a function that you want to function, and here are the simple rules:

1. The function code block begins with a def keyword, followed by the function identifier name and parentheses ().
2. Any incoming and independent variables must be placed in the middle of the parentheses. Parentheses can be used to define parameters.
3. The first line of the function can optionally use the document string-for storing the function description.
4. The function content starts with a colon and indents.
5.return[expression] Ends a function, optionally returning a value to the caller. Return without an expression is equivalent to returning None.

Grammar

Copy Code code as follows:
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

The following is a simple Python function that takes a string as an incoming parameter and then prints it to a standard display device.

Copy Code code as follows:
def printme (str):
"Print incoming string to standard display device"
Print str
Return

Second, function call
Defining a function gives only the function a name, specifies the parameters contained in the function, and the code block structure. After the basic structure of this function is complete, you can execute it through another function call, or you can execute it directly from the Python prompt.

The following instance invokes the Printme () function:

Copy Code code as follows:
#!/usr/bin/python

# Function definition is here
def printme (str):
"Print any incoming strings"
Print str;
Return

# Now, can call Printme function
Printme ("I want to call user Custom Function!");
Printme ("Call the same function again");
#以上实例输出结果:

#我要调用用户自定义函数!
#再次调用同一函数

Passing parameters by value and passing parameters by reference
All parameters (independent variables) are passed by reference in Python. If you modify the parameter in the function, the original parameter is also changed in the function that calls the function. For example:

Copy Code code as follows:
#!/usr/bin/python

# Writable Function Description
def changeme (mylist):
"Modify the Incoming list"
Mylist.append ([1,2,3,4]);
Print "function:", mylist
Return

# Call the Changeme function
MyList = [10,20,30];
Changeme (MyList);
Print "function out of Value:", MyList
#传入函数的和在末尾添加新内容的对象用的是同一个引用. The output results are as follows:

#函数内取值: [10, 20, 30, [1, 2, 3, 4]]
#函数外取值: [10, 20, 30, [1, 2, 3, 4]]

Iv. parameters of the function
Types of parameters that Python functions can use:

1. Required Parameters
2. Named parameters
3. Default parameters
4. Indefinite length parameter

1, necessary parameters

The prerequisites must pass in the function in the correct order. The number of calls must be the same as when it is declared.
To invoke the Printme () function, you must pass in a parameter, or there will be a syntax error:

Copy Code code as follows:
#!/usr/bin/python

#可写函数说明
def printme (str):
"Print any incoming strings"
Print str;
Return

#调用printme函数
Printme ();
#以上实例输出结果:

#Traceback (most recent call last):
# File "test.py", line one, in <module>
# printme ();
#TypeError: Printme () takes exactly 1 argument (0 given)


2. Named parameters

Named parameters and function calls are closely related, and the caller determines the passed-in parameter values with the name of the parameter. You can skip parameters that are not transmitted or random arguments, because the Python interpreter can match the parameter values with the name of the argument. Call the Printme () function with named arguments:

Copy Code code as follows:
#!/usr/bin/python

#可写函数说明
def printme (str):
"Print any incoming strings"
Print str;
Return

#调用printme函数
Printme (str = "my string");
#以上实例输出结果:

#My string


The following example shows more clearly the order of named parameters that are not important:
Copy Code code as follows:
#!/usr/bin/python

#可写函数说明
def printinfo (name, age):
"Print any incoming strings"
Print "Name:", name;
print ' age ', age;
Return

#调用printinfo函数
Printinfo (age=50, name= "Miki");
#以上实例输出结果:

#Name: Miki
#Age 50


3. Default parameters

When a function is called, the value of the default parameter, if not passed in, is considered the default value. The following example prints the default age if age is not passed in:

Copy Code code as follows:
#!/usr/bin/python

#可写函数说明
def printinfo (name, age = 35):
"Print any incoming strings"
Print "Name:", name;
print ' age ', age;
Return

#调用printinfo函数
Printinfo (age=50, name= "Miki");
Printinfo (name= "Miki");
#以上实例输出结果:

#Name: Miki
#Age 50
#Name: Miki
#Age 35

4, indefinite length parameter

You may need a function to handle more arguments than you originally declared. These parameters are called indefinite parameters and are not named when declared, unlike the 2 parameters mentioned above. The basic syntax is as follows:

Copy Code code as follows:
def functionname ([Formal_args,] *var_args_tuple):
"Function _ Document String"
Function_suite
return [expression]

The variable name with an asterisk (*) holds all the unnamed variable parameters. You can also select a parameter that does not have multiple passes. The following example:
Copy Code code as follows:
#!/usr/bin/python

# Writable Function Description
def printinfo (Arg1, *vartuple):
"Print any incoming parameters"
Print "Output:"
Print Arg1
For Var in vartuple:
Print Var
Return

# Call the Printinfo function
Printinfo (10);
Printinfo (70, 60, 50);
#以上实例输出结果:

#输出:
#10
#输出:
#70
#60
#50

Five, anonymous function
You can create small anonymous functions with lambda keywords. This function derives its name from a standard step that omits the declaration of a function with def.

A lambda function can receive any number of arguments but can only return the value of one expression, and can only contain a command or multiple expressions.
Anonymous functions cannot call print directly because the lambda requires an expression.
A lambda function has its own namespace and cannot access parameters outside of its own argument list or in the global namespace.
Although a lambda function may seem to write only one row, it is not the same as the C or C + + inline function, which is designed to invoke small functions without consuming stack memory and thereby increase operational efficiency.
Grammar

The syntax for a lambda function contains only one statement, as follows:

Copy Code code as follows:
Lambda [arg1 [, Arg2,..... argn]]:expression

The following example:
Copy Code code as follows:
#!/usr/bin/python

#可写函数说明
sum = lambda arg1, arg2:arg1 + arg2;

#调用sum函数
Print "Value of total:", sum (10, 20)
Print "Value of total:", sum (20, 20)
#以上实例输出结果:

#Value of Total:30
#Value of Total:40

Vi. about return statements
Return statement [expression] exits a function, optionally returning an expression to the caller. Return statement with no parameter value returns none. None of the previous examples showed how to return a value, and the following example tells you what to do:

Copy Code code as follows:
#!/usr/bin/python

# Writable Function Description
def sum (arg1, arg2):
# returns 2 parameters of the and. '
Total = Arg1 + arg2
Print "Inside the function:", total
return total;

# Call the SUM function
Total = SUM (10, 20);
Print "Outside the function:", total
#以上实例输出结果:

#Inside the Function:30
#Outside the Function:30


Vii. Scope of variables
All variables of a program are not accessible in any location. Access rights determine where the variable is assigned.

The scope of a variable determines which part of the program you can access by which particular variable name. The two most basic variable scopes are as follows:
1. Global variables
2. Local Variables

VIII. variables and local variables
Variables defined within a function have a local scope defined as having global scope outside the function.

Local variables can only be accessed within the function that they are declared, and 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:

Copy Code code as follows:
#!/usr/bin/python

Total = 0; # This is global variable.
# Writable Function Description
def sum (arg1, arg2):
#返回2个参数的和. "
Total = Arg1 + arg2; # Total is a local variable here.
Print "Inside", Total: "
return total;

#调用sum函数
SUM (10, 20);
print ' Outside the function global total: ', total
#以上实例输出结果:

#Inside the function local total:30
#Outside the function Global total:0

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.