Python Custom function creation, invocation, and arguments for functions

Source: Internet
Author: User
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 make your own creative functions, which are called user-defined functions.
First, 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 the DEF keyword, followed by the function identifier name and parentheses ().
2. Any incoming parameters and arguments must be placed in the middle of the parentheses. Parentheses can be used to define parameters.
3. The first line of the function statement can optionally use the document string-for storing function descriptions.
4. Function contents start with a colon and indent.
5.return[expression] End Function, optionally returning a value to the caller. Return without an expression is equivalent to returning None.

Grammar
Copy the 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

Here is a simple Python function that takes a string as an incoming parameter and prints it to a standard display device.
Copy the Code code as follows:

def printme (str):
"Print the incoming string on the standard display device"
Print str
Return

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

#!/usr/bin/python

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

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

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

Iii. passing parameters by value and passing parameters by reference
All parameters (independent variables) are passed by reference in Python. If you modify the parameters in the function, the original parameters are changed in the function that called the function. For example:
Copy the Code code as follows:

#!/usr/bin/python

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

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

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

Iv. parameters of the function
The type of arguments the Python function can use:

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

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

#!/usr/bin/python

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

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

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


2. Named parameters

Named arguments and function calls are closely related, and the caller determines the passed-in parameter value with the name of the parameter. You can skip arguments that do not pass or sequence the arguments, because the Python interpreter can match parameter values with the name of the argument. Call the Printme () function with a named parameter:
Copy the Code code as follows:

#!/usr/bin/python

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

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

#My string


The following example shows that the order of named parameters is not important to show more clearly:
Copy CodeThe code is as follows:

#!/usr/bin/python

#可写函数说明
def printinfo (name, age):
"Print any incoming string"
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 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:
Copy the Code code as follows:

#!/usr/bin/python

#可写函数说明
def printinfo (name, age = 35):
"Print any incoming string"
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 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:
Copy the Code code 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. Choose not to send more parameters can also. The following example:
Copy CodeThe code is as follows:

#!/usr/bin/python

# Writable Function Description
def printinfo (Arg1, *vartuple):
"Print any parameters passed in"
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
Use lambda keywords to create small anonymous functions. This function is named after the standard procedure for declaring a function with DEF is omitted.

A lambda function can receive any number of arguments but can only return the value of an expression, and can only contain commands or multiple expressions.
Anonymous functions cannot call print directly, because lambda requires an 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:
Copy the Code code as follows:

Lambda [arg1 [, Arg2,..... argn]]:expression


The following example:
Copy CodeThe code is 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 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:
Copy the Code code as follows:

#!/usr/bin/python

# Writable Function Description
def sum (arg1, arg2):
# returns the and of 2 parameters.
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 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:
1. Global variables
2. Local Variables

VIII. 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:
Copy the 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 the function local total:"
return total;

#调用sum函数
SUM (10, 20);
Print "Outside the function global 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.