Getting Started with function usage in Python

Source: Internet
Author: User
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 program design. The specific analysis is as follows:

First, the definition of the function:

Python uses the DEF keyword to define a function, which includes the function name and parameters, does not need to define a return type, 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 none  # The parameter def run (name) with the return value:     

Second, the document string:

In Python, comments are represented by #, and no multiline comments are found yet. However, you can use a multiline string to write inside a function:

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

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

Three, Parameters:

The parameter list of a Python function can be any number, call the function, take the position binding and the keyword binding two ways, confirm the parameters of the passed variables!

The code shown above can be considered a positional binding.

Here's a look at the keyword bindings:

def run (name,age,sex):     

A parameter cannot use the position and keyword bindings at the same time in a single call

def run (name,age,sex):     

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

Default parameters:

def run (name,age=20,sex= ' Girl '):     print Name,age,sex >>>run (' Nana ') Nana girl >>>run (' Nana ', Nana girl >>>run (' gg ', ' Boy ') #使用的位置绑定, so python binds ' boy ' to age, not the sex we want GG boy girl  

1, if a function parameter contains a default parameter, 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):     

Several exceptions

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

#第一种情况是丢失参数
#第二种情况是: If the first keyword binding is used, the following must use the keyword binding
#第三种情况: You cannot use both location and keyword bindings in a single call
#第四种情况: You cannot use a keyword outside the argument list

2. The default parameters are parsed in the function definition segment and resolved only once.

>>>i = 5 >>>def f (arg=i): >>>  

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

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

Variable parameters

Parameters are wrapped into a tuple. Before these variable number of parameters, there can be 0 to more common parameters:

def run (Name,*args):     print name, ' runing ' for     A in Args:print a  

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

The variable parameter of the keyword binding (**args this form, see the original document, not very understanding, for the moment 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 **args def run (name,*a Rg,**args): For     A in arg:p rint a     keys = Args.keys () for     K in keys:        

Splitting of parameter columns

>>> Range (3, 6)       # Normal call with separate arguments [3, 4, 5] >>> args = [3, 6] >>> range (*args)      

By using 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), set the value of N >>> F (0) #其实调用的是匿名函数? >>> f (1)  #看下面一个例子报的错误就可以明白一点了 >>>def t (n): ...     Print X*n >>>m = t (2) Traceback (most recent call last):  File "
 
  
   
  ", line 1, in 
  
   
    
      m = t (2)  File "
   
    
     
    ", line 2, in T   print x*n nameerror:global name ' x ' are not defined 
   
    
  
   
   
  

Says no global name ' x ' is defined

>>> x =10 >>> def t (n): ...    

Hopefully this article will help you with Python programming.

  • 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.