Latest web development tutorials

Python function

Function is a good organization, reusable, used to achieve a single code segment, or associated functions.

Function can be applied to improve the modularity and reuse code. You already know that Python provides many built-in functions, such as print (). But you can also create your own function, which is called a user-defined function.


Define a function

You can define a function from the function you want, the following simple rules:

  • Function block def keyword in the beginning, followed by the function name and identifiers in parentheses ().
  • Any incoming parameters and arguments must be placed in parentheses in the middle. It can be used to define the parameters between parentheses.
  • The first line of the function statement can optionally use a string document - are used for function description.
  • Function content starting with a colon and indentation.
  • return [expression] end of the function, optionally return a value to the caller. return without an expression equivalent to return None.

grammar

def functionname( parameters ):
   "函数_文档字符串"
   function_suite
   return [expression]

By default, the parameter name and parameter value is in the order defined in the function declaration matches up.

Examples

The following is a simple Python function, passing it a string as a parameter, then print to the standard display device.

def printme( str ):
   "打印传入的字符串到标准显示设备上"
   print str
   return

Function call

Define a function only to a function name, specify the parameters, and code block structure contains the function.

After completion of the basic structure of this function, you can perform another function call to be executed directly from the Python prompt.

The following examples are called printme () function:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 定义函数
def printme( str ):
   "打印任何传入的字符串"
   print str;
   return;
 
# 调用函数
printme("我要调用用户自定义函数!");
printme("再次调用同一函数");

Examples of the above output:

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

Parameters passed by value and pass parameters by reference

All parameters (arguments) in Python are passed by reference. If you change a parameter in a function, then this function is called function, the original parameters are also changed. E.g:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 可写函数说明
def changeme( mylist ):
   "修改传入的列表"
   mylist.append([1,2,3,4]);
   print "函数内取值: ", mylist
   return
 
# 调用changeme函数
mylist = [10,20,30];
changeme( mylist );
print "函数外取值: ", mylist

And passed into the function of the object at the end to add new content using the same reference. So the output results are as follows:

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

parameter

The following is the formal parameter type can be used when calling the function:

  • Mandatory parameter
  • Keyword arguments
  • The default parameters
  • Variable-length parameters

Mandatory parameter

Mandatory parameter to be passed to the function in the correct order. When the number of calls and must be the same declaration.

Call printme () function, you must pass in a parameter, or syntax error will occur:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
#可写函数说明
def printme( str ):
   "打印任何传入的字符串"
   print str;
   return;
 
#调用printme函数
printme();

Examples of the above output:

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

Keyword arguments

Keyword arguments and function calls a close relationship function call using keyword arguments to determine the value of the parameter passed.

When using the keyword parameter allows the function call order parameter is inconsistent with the statement, because Python interpreter capable of matching the parameter values ​​using the parameter name.

The following example function printme () is called with the parameter name:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
#可写函数说明
def printme( str ):
   "打印任何传入的字符串"
   print str;
   return;
 
#调用printme函数
printme( str = "My string");

Examples of the above output:

My string

The following example can order keyword argument is not important show more clearly:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
#可写函数说明
def printinfo( name, age ):
   "打印任何传入的字符串"
   print "Name: ", name;
   print "Age ", age;
   return;
 
#调用printinfo函数
printinfo( age=50, name="miki" );

Examples of the above output:

Name:  miki
Age  50

The default parameters

When the function is called, the default value if the parameter is not passed, the default value is considered. By default print regular meeting of age, if age is not passed:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
#可写函数说明
def printinfo( name, age = 35 ):
   "打印任何传入的字符串"
   print "Name: ", name;
   print "Age ", age;
   return;
 
#调用printinfo函数
printinfo( age=50, name="miki" );
printinfo( name="miki" );

Examples of the above output:

Name:  miki
Age  50
Name:  miki
Age  35

Variable-length parameters

You may need a function that can handle more than the original declaration of parameters. These parameters are called the variable length parameters, and the two types of parameters are different, not naming declaration. The basic syntax is as follows:

def functionname([formal_args,] *var_args_tuple ):
   "函数_文档字符串"
   function_suite
   return [expression]

With an asterisk (*) will be stored in variable names all unnamed variable parameters. Pass parameters may be little choice. The following examples:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 可写函数说明
def printinfo( arg1, *vartuple ):
   "打印任何传入的参数"
   print "输出: "
   print arg1
   for var in vartuple:
      print var
   return;
 
# 调用printinfo 函数
printinfo( 10 );
printinfo( 70, 60, 50 );

Examples of the above output:

输出:
10
输出:
70
60
50

Anonymous function

python using lambda to create an anonymous function.

  • Just a lambda expression, the function body is much simpler than def.
  • The body is a lambda expression, rather than a block of code. We can only package a limited logic into the lambda expression.
  • lambda function has its own namespace, and can not be accessed outside of its own argument list or the global namespace parameters.
  • Although lambda function looks only write a single line, but not the same as inline functions in C or C ++, the latter purpose is not occupied when calling the small stack memory function to increase operating efficiency.

grammar

Lambda function syntax contains only one statement, as follows:

lambda [arg1 [,arg2,.....argn]]:expression

The following examples:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 可写函数说明
sum = lambda arg1, arg2: arg1 + arg2;
 
# 调用sum函数
print "相加后的值为 : ", sum( 10, 20 )
print "相加后的值为 : ", sum( 20, 20 )

Examples of the above output:

相加后的值为 :  30
相加后的值为 :  40

return statement

Statement return [expression] to exit function selectively to the caller returns an expression. return statement with no parameters returns None. No previous examples demonstrate how to return a value, the following example will show you how to do it:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 可写函数说明
def sum( arg1, arg2 ):
   # 返回2个参数的和."
   total = arg1 + arg2
   print "函数内 : ", total
   return total;
 
# 调用sum函数
total = sum( 10, 20 );

Examples of the above output:

函数内 :  30

Variable Scope

All the variables in a program which is not a position that can be accessed. Access depends on where the variable is assigned.

Scope of a variable determines which part of the program in which you can access a particular variable name. Two basic variable scope as follows:

  • Global Variables
  • Local variables

Global and local variables

The definition of the function of internal variables have a local scope, as defined in the outer function has global scope.

Local variables can only be declared inside a function of its access to global variables can be accessed throughout the procedures. When you call a function, all variable names in function declarations will be added to the scope. The following examples:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

total = 0; # 这是一个全局变量
# 可写函数说明
def sum( arg1, arg2 ):
   #返回2个参数的和."
   total = arg1 + arg2; # total在这里是局部变量.
   print "函数内是局部变量 : ", total
   return total;
 
#调用sum函数
sum( 10, 20 );
print "函数外是全局变量 : ", total 

Examples of the above output:

函数内是局部变量 :  30
函数外是全局变量 :  0