Examples of learning notes using Python functions

Source: Internet
Author: User
Tags anonymous define function variable scope in python

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 and independent arguments must be placed in the middle of the parentheses. Parentheses can be used to define parameters.
The first line of the function can optionally use the document string-for storing the function description.
The function content starts with a colon and indents.
Return[expression] Ends a 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
The following is a simple Python function that takes a string as an incoming parameter and then prints it to a standard display device.

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

--------------------------------------------------------------------------------

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:

#!/usr/bin/python
#-*-Coding:utf-8-*-

# define function
def printme (str):
"Print any incoming strings"
Print str;
Return

# Call function
Printme ("I want to call user Custom Function!");
Printme ("Call the same function again");
The above example outputs the result:

I want to call user-defined functions!
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:

#!/usr/bin/python
#-*-Coding:utf-8-*-

# 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 same reference is used for objects that pass into the function and add new content at the end. The output results are as follows:

function values: [10, 20, 30, [1, 2, 3, 4]]
function out values: [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
Named parameters
Default parameters
Indefinite length parameter
Required 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:

#!/usr/bin/python
#-*-Coding:utf-8-*-

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

#调用printme函数
Printme ();
The above example outputs the result:

Traceback (most recent call last):
File "test.py", line one, in <module>
Printme ();
Typeerror:printme () takes exactly 1 argument (0 given)
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:

#!/usr/bin/python
#-*-Coding:utf-8-*-

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

#调用printme函数
Printme (str = "my string");
The above example outputs the result:

My string
The following example shows more clearly the order of named parameters that are not important:

#!/usr/bin/python
#-*-Coding:utf-8-*-

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

#调用printinfo函数
Printinfo (age=50, name= "Miki");
The above example outputs the result:

Name:miki
Age 50
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:

#!/usr/bin/python
#-*-Coding:utf-8-*-

#可写函数说明
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");
The above example outputs the result:

Name:miki
Age 50
Name:miki
Age 35
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:

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:

#!/usr/bin/python
#-*-Coding:utf-8-*-

# 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);
The above example outputs the result:

Output:
10
Output:
70
60
50

--------------------------------------------------------------------------------

anonymous functions
Python uses a lambda to create anonymous functions.

A 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. Can only encapsulate limited logic in lambda expressions.
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:

Lambda [arg1 [, Arg2,..... argn]]:expression
The following example:

#!/usr/bin/python
#-*-Coding:utf-8-*-

# Writable Function Description
sum = lambda arg1, arg2:arg1 + arg2;

# Call the SUM function
Print "Adds a value of:", SUM (10, 20)
Print "Adds a value of:", SUM (20, 20)
The above example outputs the result:

The added value is: 30
The added value is: 40

--------------------------------------------------------------------------------

Return statement
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:

#!/usr/bin/python
#-*-Coding:utf-8-*-

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

# Call the SUM function
Total = SUM (10, 20);
Print "Outside of function:", total
The above example outputs the result:

Inside function: 30
Outside function: 30

--------------------------------------------------------------------------------

Variable scope
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:

Global variables
Local variables

--------------------------------------------------------------------------------

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:

#!/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.
Print "function is a local variable:", total
return total;

#调用sum函数
SUM (10, 20);
Global variable outside of print function: ", total
The above example outputs the result:

Inside a function is a local variable: 30
Global variables outside the function: 0

Python has many built-in functions that are generally easier to understand and invoke
For example, a commonly used data type conversion int function
A=int (' 123 ')
Print (a)
Return 123

In fact, many times you need a custom function, and the custom function uses the DEF statement in the following format:
def function name (parameters):
Statement
Return
To do a simple addition function
A=input (' a= ')
B=input (' b= ')
C=int (a)
D=int (b)

def sum (x,y):
Sum=x+y
return sum
Print (sum (c,d))
The result is returned to 3.

More complex is a multi-parameter function, such as entering a number, and seeking its n-th side.
A=int (Input (' a= '))
B=int (Input (' Chengfang '))
def CF (X,y):
S=1
While y>0:
Y=y-1
S=s*x
return s
Print (cf (A,B))
An error occurs when the argument is not entered, and you can set a default value for the parameter of the function, CF (x,y=2).

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.