1-14 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.


The definition of a function

You may want to define a function by their own functions, the following simple rules:

  • In function block  def  beginning keyword, followed by the name and function identifier parentheses  () .
  • Any incoming parameters and arguments in parentheses must be placed in the middle, 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 .

grammar

Python custom function uses def keyword, the following general format:

def function name (parameter list):
    Function body

By default, the parameter name and the parameter value is defined in order to match the function declaration together.

Examples

Let's use the function to output "Hello World!":

>>>def hello() :
   print("Hello World!")
 
   
>>> hello()
Hello World!
>>>

Application of more complex point, take the function parameter variables:

#!/usr/bin/python3
 
# 计算面积函数
def area(width, height):
    return width * height
 
def print_welcome(name):
    print("Welcome", name)
 
print_welcome("Runoob")
w = 4
h = 5
print("width =", w, " height =", h, " area =", area(w, h))

Examples of the above output:

Welcome Runoob
width = 4  height = 5  area = 20

Function call

Definition of a function: the 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 performed by another function can be performed directly from the Python command prompt.

The following examples called  PrintMe ()  function:

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

Examples of the above output:

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

Parameter passing

In python, belong to the object type, the variable type is not:

a=[1,2,3]

a="Runoob"

Above, the [1,2,3]  type 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 point List, may be is a pointer to an object of type String.

You can change the (mutable) and can not be changed (immutable) objects

In python, strings, tuples, and the numbers are not subject to change, and list, dict and so it can be modified objects.

  • Immutable type: Variable Assignment  a = 5  then the assignment  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]  then assigned  la [2] = 5  third element values change 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 type: 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, does not affect a per se.

  • Variable Type: 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

python, everything is an object, we can not say the strict sense of the value passed by reference or pass, we should say pass immutable objects and pass variable objects.

python mass immutable object instance

#!/usr/bin/python3
 
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

Mutable objects modify the parameters in the function, then the function call this function, the original parameters have been changed. E.g:

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

Passed into the function and add new content at the end of the object is the same with a 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:

  • Required parameters
  • Keyword arguments
  • The default parameters
  • Variable-length parameters

Required parameters

Required 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/python3
 
#可写函数说明
def printme( str ):
   "打印任何传入的字符串"
   print (str)
   return
 
#调用printme函数
printme()

Examples of the above output:

Traceback (most recent call last):
  File "test.py", line 10, in <module>
    printme()
TypeError: printme() missing 1 required positional argument: 'str'

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/python3
 
#可写函数说明
def printme( str ):
   "打印任何传入的字符串"
   print (str)
   return
 
#调用printme函数
printme( str = "菜鸟教程")

Examples of the above output:

Rookie Tutorial

The following examples demonstrate the need to use a function of parameters used in the specified order:

#!/usr/bin/python3
 
#可写函数说明
def printinfo( name, age ):
   "打印任何传入的字符串"
   print ("名字: ", name)
   print ("年龄: ", age)
   return
 
#调用printinfo函数
printinfo( age=50, name="runoob" )

Examples of the above output:

名字:  runoob
年龄:  50

The default parameters

When you call the function, if the parameter is not passed, the default parameters will be used. The following examples if no incoming age parameter, the default value:

#!/usr/bin/python3
 
#可写函数说明
def printinfo( name, age = 35 ):
   "打印任何传入的字符串"
   print ("名字: ", name)
   print ("年龄: ", age)
   return
 
#调用printinfo函数
printinfo( age=50, name="runoob" )
print ("------------------------")
printinfo( name="runoob" )

Examples of the above output:

名字:  runoob
年龄:  50
------------------------
名字:  runoob
年龄:  35

Variable-length parameters

You may 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 * parameter will be introduced as a tuple (tuple), and storage of all variables unnamed parameters.

#!/usr/bin/python3
  
# 可写函数说明
def printinfo( arg1, *vartuple ):
   "打印任何传入的参数"
   print ("输出: ")
   print (arg1)
   print (vartuple)
 
# 调用printinfo 函数
printinfo( 70, 60, 50 )

Examples of the above output:

输出: 
70
(60, 50)

 

If no argument in the function call, it is an empty tuple. We can not pass variables to unnamed function. Following examples:

#!/usr/bin/python3
 
# 可写函数说明
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

Another is the parameter with two asterisks ** The basic syntax is as follows:

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

Plus two asterisks ** parameters will be introduced as a dictionary.

#!/usr/bin/python3
  
# 可写函数说明
def printinfo( arg1, **vardict ):
   "打印任何传入的参数"
   print ("输出: ")
   print (arg1)
   print (vardict)
 
# 调用printinfo 函数
printinfo(1, a=2,b=3)

Examples of the above output:

输出: 
1
{'a': 2, 'b': 3}

When you declare a function argument asterisk * can occur alone, for example:

def f(a,b,*,c):
    return a+b+c

If the parameters asterisk * must be passed separately after the keyword.

>>> def f(a,b,*,c):
...     return a+b+c
... 
>>> f(1,2,3)   # 报错
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() takes 2 positional arguments but 3 were given
>>> f(1,2,c=3) # 正常
6
>>>

Anonymous function

python using lambda to create an anonymous function.

The so-called anonymous, which means no longer use this standard form def statement defines a 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 its own parameter 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.

grammar

Lambda function syntax contains only one statement, as follows:

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

Following examples:

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

Examples of the above output:

The added value: 30
The added value: 40

return statement

return [Expression]  statement to leave a function, an expression is selectively returned to the caller. Return statement with no parameter values return None. No previous examples demonstrate how to return a value, the following example demonstrates the use of the return statement:

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

Examples of the above output:

Within the function: 30
Outside the function: 30

Variable Scope

Python, variables in the program is not in any position that can be accessed, access depends on where the variable is assigned.

Scope of a variable determines which part of a program in which a particular variable name can be accessed. Python's scope, a total of four kinds, namely:

  • L (Local) local scope
  • E (Enclosing) function outside the closure function
  • G (Global) global scope
  • B (Built-in) built scope (where the scope of the built-in function module)

To L -> E -> G - Rules> B lookup, namely: not found locally, will find a local (e.g., closure) to the outer partial, you will not find to find the global, addition to built-in look.

g_count = 0  # 全局作用域
def outer():
    o_count = 1  # 闭包函数外的函数中
    def inner():
        i_count = 2  # 局部作用域

Built-in scope is achieved by a standard module called builtin, but the variable name itself is not built into the scope, so must import the files before you can use it. In Python3.0, you can use the following code to see in the end what predefined variables:

>>> import builtins
>>> dir(builtins)

Only Python module (Module1), class (class) and a function (def, lambda) before introducing a new scope, the other block of code (e.g., if / elif / else /, try / except, for / while, etc.) does not introduce a new scope, that variable defined within these statements, external can visit the following code:

>>> if True:
...  msg = 'I am from Runoob'
... 
>>> msg
'I am from Runoob'
>>> 

Msg variable is defined in the example if block but still be accessible outside.

If msg is defined in the function, then it is a local variable, not external access:

>>> def test():
...     msg_inner = 'I am from Runoob'
... 
>>> msg_inner
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'msg_inner' is not defined
>>> 

From the point of view of information being given, it explained msg_inner not defined, can not be used because it is a local variable, can be used only within the function.


Global and local variables

It is defined as having a local scope, defined outside the function has global scope within a function of the variables.

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/python3
 
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

global and nonlocal keyword

When you want to modify the scope of internal variables outer scope, it is necessary to use a global and nonlocal keyword.

The following examples modify global variables num:

num = 1
def fun1():
    global num  # 需要使用 global 关键字声明
    print(num) 
    num = 123
    print(num)
fun1()
print(num)

Examples of the above output:

1
123
123

To modify nested scopes (the enclosing scope, the outer non-global scope) variables nonlocal keyword is required, as the following examples:

 
def outer():
    num = 10
    def inner():
        nonlocal num   # nonlocal关键字声明
        num = 100
        print(num)
    inner()
    print(num)
outer()

Examples of the above output:

100
100

There is another special case, suppose the following code is executed:

#!/usr/bin/python3
 
a = 10
def test():
    a = a + 1
    print(a)
test()

Above program is run, the following error message:

Traceback (most recent call last):
  File "test.py", line 7, in <module>
    test()
  File "test.py", line 5, in test
    a = a + 1
UnboundLocalError: local variable 'a' referenced before assignment

Error message for the local scope misquoted, because the function of a test using a local, undefined, can not be modified.

Modifying a global variable, function parameters are passed through, the normal execution result is output:

a = 10
def test(a):
    a = a + 1
    print(a)
test(a)

Execution output is:

11

Guess you like

Origin blog.csdn.net/u012717715/article/details/91962037