Introductory tutorial on functional usage in Python _python

Source: Internet
Author: User
Tags function definition in python

In this paper, the use of functions in Python programming is described in detail, which has a good reference value for the study of Python programming. The specific analysis is as follows:

Definition of a function:

Python uses the DEF keyword to define functions, which include function names and parameters, and do not need to define return types, and Python can return any type:

#没有返回值的函数, it actually returns the None 
def run (name): 
    print name, ' runing ' #函数体语句从下一行开始, and the first line must be indented 
 
>>>run (' Xiaoming ') 
xiaoming runing 
 
>>>print run (' xiaoming ') 
xiaoming runing 
None #如果没有ruturn语句, function returns the None 
 
#有返回值的参数 
def Run (name): Return 
    name+ ' runing ' 
>>>r = run (' xiaoming ') 
>>>r 
xiaoming runing 

Second, the document string:

In Python, annotations are represented by #, and no multiline annotation is found for the time being. However, within a function, you can use multiple lines of string to write:

def run (name): "" " 
    Print Somebody runing" "#写在函数体的第一行才叫文档字符串 
    Print name, ' runing '  

You can use __doc__ to view the contents of a function's document string

>>>run.__doc__ 
Print Somebody runing 

Third, Parameters:

Python's function of the parameter list can be any number, call the function, take the position binding and keyword binding two ways to confirm the parameters of the incoming variable!

The code shown above can be considered a position binding.

Here's a look at the keyword bindings:

def run (name,age,sex): 
    print ' name: ', Name, ' Age: ', age, ' Sex: ', sex 
>>> run (age=23,name= ' xiaoming ', sex= ' boy ') #关键字绑定 
name:xiaoming age:23 sex:boy 

A parameter cannot use both location and keyword binding in one call

def run (name,age,sex): 
    print ' name: ', Name, ' Age: ', age, ' Sex: ', sex 
>>> run (' xiaoming ', name= ') Xiaoming ', sex= ' boy ') 
syntaxerror:non-keyword arg after keyword arg 

When a function is called, if the first argument uses a keyword binding, the following argument must also be bound with a keyword!

Default parameters:

def run (name,age=20,sex= ' Girl '): 
    print name,age,sex 
>>>run (' Nana ') 
nana girl 
>> >run (' Nana ', s) 
nana girl 
>>>run (' gg ', ' Boy ') #使用的位置绑定, so python binds ' boy ' to age rather than the sex we want 
gg Boy girl 
 
>>>run (' gg ', sex= ' boy ') #混合关键字绑定, you can achieve the desired effect of 
GG Boy 

1, if the parameter of a function contains default parameters, then all parameters after this default parameter must be the default parameter, otherwise it will throw: syntaxerror:non-default argument follows default argument exception.

def run (name,age=10,sex): 
    print name, age, sex 
syntaxerror:non-default argument follows default argument GG 23 Boy 

Several exceptions

def run (name,age,sex= ' Boy '): 
    print Name,age,sex 

>>>run () #required argument missing 
>> >run (name= ' GG ') #non-keyword argument following keyword >>>run 
(' gg ', name= ' pp ') #duplicate value For argument 
>>>run (actor= ' xxxx ') #unknown keyword 

#第一种情况是丢失参数
#第二种情况是: If the first one uses the keyword binding, then the keyword binding must be used later
#第三种情况: Cannot use both location and keyword bindings in one call
#第四种情况: Cannot use a keyword outside of the argument list

2. The default parameter is parsed in the function definition segment and is parsed only once.

>>>i = 5 
>>>def f (arg=i): 
>>>  print arg 
>>>i = 6 
> >>f () 
5 #结果是5 

When the default value is a Mutable object, such as a linked list, dictionary, or most class instance, some differences occur:

>>> def f (A, l=[]): 
>>>  l.append (a) 
>>> return  L 
 
>>> print F (1) 
>>> print F (2) 
>>> print F (3) 
[1] 
[1, 2] 
[1, 2, 3] 
 
#可以用另外一种方式实现: 
> >> def f (A, L=none): 
>>>  if L is None: 
>>>    L = [] 
>>>  L.append (a) 
>>> return  L 

Variable parameters

parameter is wrapped into a tuple. Before these variable-number parameters, you can have 0 to more than one normal parameter:

def run (Name,*args): 
    print name, ' runing ' for 
    A in Args:print a 
 
>>> run (' GG ', ' mm ') 
GG runing 
mm 
>>> run (' GG ', 1,2, ' mm ') 
gg runing 
1 
2 
mm 
>>> run (' GG ', 1,1.02,[' mm ', ' GM '] 
gg runing 
1 
1.02 
[' mm ', ' GM '] 

Visible variable parameters can be any number of, and are any type (and can be mixed)

Variable parameters for keyword binding (**args this form, see the original document, do not understand, this is called)

def run (Name,**args): 
    keys = Args.keys () 
    for k in keys: 
       print K,args[k] 
 
>>> run (' Nana ', type= ') Open ') 
type open 
>>> run (' Nana ', type= ' open ', title= ' Gogo ') 
type open 
title Gogo 

#*arg Must be in front of the **args 
def Run (Name,*arg,**args): For 
    A in arg:p rint a 
    keys = Args.keys () for 
    K in keys: 
       Print K,args[k] 
>>> run (' nn ', ' mm ', 1,2, ' oo ', type= ' open ', title= ' Gogo ') 
mm 
1 
2 
oo 
type Open 
title Gogo 

Splitting of parameter columns

>>> Range (3, 6)       # Normal call with separate arguments 
[3, 4, 5] 
>>> args = [3, 6] 
&G T;>> Range (*args)      # Call with arguments unpacked from a list 
[3, 4, 5] 

With the Lambda keyword, you can create short anonymous functions

>>> def make_incrementor (n): 
...   return lambda x:x + n #相当于创建了一个一x为参数的匿名函数? 
... 
>>> f = make_incrementor #f = Make_incrementor (n=42), setting the value of n 
>>> F (0) #其实调用的是匿名函数? 
>>> F (1) 
 
#看下面一个例子报的错误就可以明白一点了 
>>>def t (n): 
...     Print X*n 
>>>m = t (2) 
Traceback (most recent call last): 
 File ' <pyshell#85> ', line 1, ;module> 
  m = t (2) 
 File "<pyshell#84>", line 2, in T 
  print x*n 
nameerror:global name ' x ' n OT defined 

Said is not defined global name ' x '

>>> x =10 
>>> def t (n): 
...    Print X*n 
>>> m = t (2) 
20 

I hope this article will help you with your Python programming.

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.