How to use Python function

Tissue function is good, reusable, code segments used to implement a single, or the associated function.
Function module of the application can be improved, and code reuse. You already know that Python provides many built-in functions, such as print (). But you can also create your own functions, which are called user-defined functions.
Define a function
you can define a function of the desired function by themselves, the following rules are simple:
the function code block begins with def keyword followed by the function name and identifiers in parentheses ().
Any incoming parameters and arguments must be placed in the middle of parentheses. Between parentheses may be used to define the parameters.
The first statement function can be selectively used documentation string - for storing function instructions.
Start function contents colon, and indentation.
return [Expression] End function, selectively returns a value to the caller. Return without an expression equivalent to return None.

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

By default, the parameter name and the parameter value is defined in order to match the function declaration together.
Examples
The following is a simple function of the Python, as a string parameter passed it, and then to print on the standard display apparatus.

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

Function call
to define a function only as a function of a given name, contains parameters specifying the function, and the code block structure.
After completion of the basic structure of this function, you can call the function performed by another, can be executed directly from Python prompt.
The following examples PrintMe call () function:

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

# 定义函数
def printme( str ):
   "打印任何传入的字符串"
   print str
   return

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

Examples of the above output:

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

Parameters passed
in python, belong to the object type, the variable type is not:

a=[1,2,3]

a="Runoob"

Above, the [1,2,3] type is List, "Runoob" is of type String, and the variable is not a type, she is just an object reference (a pointer), the type of the object may be a List can also point String type object.
Can be changed (the mutable) and can not be changed (the immutable) objects
in python, strings, tuples, and numbers are immutable objects, the list, dict the other objects can be modified.
Immutable type: a = 5 Variable Assignment Assignment then a = 10, where int is actually generate a new value object 10, a point let it be discarded and 5, instead of changing the value of a, a is newly equivalent .
Variable Type: Variable Assignment la = [1,2,3,4] la assignment after the third element [2] = 5 to change the value sucked List la, la in itself did not move, only part of the value of its internal It is modified.
python parameter transfer function:
immutable: the similarity value passed c ++, such as integer, string, a tuple. The value Fun (a), only a transfer of a subject itself has no effect. Such modifications (a) an internal value of a fun, but modify the object copied to another, it does not affect a per se.
Variable types: Similar to c ++ is passed by reference, such as lists, dictionaries. As fun (la), sucked la real pass in the past, the revised fun outside la also be affected
everything is an object in python, in the strict sense we can not say passed by reference or value transfer, we should say pass immutable objects and pass variable objects.
python mass immutable object instance

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

def ChangeInt( a ):
    a = 10

b = 2
ChangeInt(b)
print b # 结果是 2

Instance there int objects 2, pointing to its variables b, when passed to ChangeInt function, by way of traditional values copied variable b, a and b point to the same Int object, a = 10, then the new generating an int value object 10, and let a point to it.
Object instance variable transmission

#!/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

Examples of afferent functions and add new content at the end of the object with a reference to the same, so the output results are as follows:

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

Parameters
The following are the formal parameter type can be used when calling a function:
an essential parameter
keyword arguments
default parameters for
variable length parameters
necessary parameters
necessary parameters to be passed to the function in the correct order. When the number of calls and the same must be declared when.
Call printme () function, you must pass in a parameter, or will a syntax error:

#!/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 call close relationship function call using keywords to determine the parameters passed in parameter values.
When you use keyword parameters and allows the order parameter of the function call statement is inconsistent, because the Python interpreter to match the parameter value with the parameter name.
The following example uses the parameter name when you call the function printme ():

#!/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 key parameter order 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 parameter
function is called, the default value if the parameter is not passed, is considered to be the default. Under regular printing the default 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 might need a function that can handle more parameters than the original statement. These parameters, called variable length parameters, and the two kinds of different parameters, not naming declaration. The basic syntax is as follows:

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

Plus an asterisk (*) will be stored in the variable name for all variables unnamed parameters. Examples of variable-length parameters as follows:

#!/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, function body is much simpler than def.
lambda expression is a body, instead of a code block. 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 can only write a single line, but not equivalent to C or C ++ inline functions, which aims not take up the stack memory when calling small functions to increase operating efficiency.
Syntax
The syntax of lambda functions contain only a statement as follows:

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

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
return statement [Expression] to exit the function returns a selective expression to the caller. Return statement with no parameter values return None. No previous example demonstrates 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 of a program is not in any position can access. Access depends on where the variable is assigned.
Scope of a variable determines which part of a program in which specific variable names you can access. The scope of the following two basic variables:
global variables
local variables
global variables and local variables
defined as having a local scope variables inside a function, defined as having global scope outside the function.
The local variables can be declared within its access function, and can access the global variables in the entire program range. When you call a function, all variables declared within a function name will be added to the scope. 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

Guess you like

Origin blog.51cto.com/14646124/2463371