Python functions study notes -Python

Tissue function is good, reusable, code segments used to implement a single, or the associated function.

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 must be placed in the middle of parentheses. Between parentheses may be used to define the parameters.
  • Function The first row statement may then be selectively used to document the string - for storing function instructions .
  • Function contents in the colon starting , and indentation .
  • return [Expression]  End function, selectively returns a value to the caller. Return without an expression equivalent to return None.

grammar

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

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.

Example (Python 2.0+)

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

Function call

Define a function only as a function of a given name, you specify the parameters, and the block contains a function of the 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:

Example (Python 2.0+)

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

Examples of the above output:

I want to call a user-defined function! 
Again call the same function

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 a reference to an object (a pointer) can be List type object can also be directed String type object.

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

In python, strings, tuples, and numbers are immutable objects , 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 ( hard type ). The Fun (a), the value of a transmission only , does not affect a subject itself . Such modifications (a) an internal value of a fun, but modify the object copied to another, it does not affect a per se.

  • Variable Type: Similar c ++ passes a reference, such as a list of dictionary ( variable type ). As fun (la), is the true la pass in the past , the revised fun outside la also be affected

python mass immutable object instance

Example (Python 2.0+)

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

Example (Python 2.0+)

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

The function values: [10, 20, 30, [1, 2, 3, 4]] 
outer Value Function: [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

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:

Example (Python 2.0+)

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

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 ():

Example (Python 2.0+)

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

Example (Python 2.0+)

#!/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 you call the function, the value of the parameters if the default is not passed, is considered the default value . Under regular printing the default age, if age is not passed:

Example (Python 2.0+)

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

Example (Python 2.0+)

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

Output: 
10 
Output: 
70 
60 
50

Anonymous function

python using lambda to create an anonymous function.

  • lambda function has its own namespace, and the outside can not access its own argument list or the global namespace parameters .

grammar

Lambda function syntax contains only one statement, as follows:

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

Following examples:

Example (Python 2.0+)

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

The value obtained by adding: 30 
of the added value: 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:

Example (Python 2.0+)

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

Within the function: 30

Variable Scope

Scope of a variable determines which part of a program in which specific variable names you can access. Two basic variable scope as follows:

  • Global Variables
  • Local variables

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:

Example (Python 2.0+)

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

Local variables inside a function: 30 
external function is a global variable: 0
Published 19 original articles · won praise 0 · Views 811

Guess you like

Origin blog.csdn.net/weixin_44151772/article/details/104034095