"Learn Python with me" function in Python

Source: Internet
Author: User

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:

Python code
  1. #没有返回值的函数, it actually returns none.
  2. def run (name):
  3. print name,' runing ' #函数体语句从下一行开始, and the first line must be indented
  4. >>>run (' xiaoming ')
  5. Xiaoming runing
  6. >>>print run (' xiaoming ')
  7. Xiaoming runing
  8. None #如果没有ruturn语句, the function returns none
  9. #有返回值的参数
  10. def run (name):
  11. return name+' runing '
  12. >>>r = run (' xiaoming ')
  13. >>>r
  14. Xiaoming runing
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:

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

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

Java code
    1. >>>run.__doc__
    2. Print Somebody runing

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 :

Python code
    1. def run (name,age,sex):
    2. print ' name: ', name,' Age: ', age,' sex: ', sex
    3. >>> Run (age=23,name=' xiaoming ', sex=' boy ')#关键字绑定
    4. Name:xiaoming Age:sex:boy

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

Python code
    1. def run (name,age,sex):
    2. print ' name: ', name,' Age: ', age,' sex: ', sex
    3. >>> run (' xiaoming ', name=' xiaoming ', sex=' boy ')
    4. 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 use the keyword binding!

Default Parameters :

Python code
  1. def run (name,age=20,sex=' girl '):
  2. Print Name,age,sex
  3. >>>run (' nana ')
  4. Nana Girl
  5. >>>run (' nana ', +)
  6. Nana Girl
  7. >>>run (' GG ',' boy ')#使用的位置绑定, so python binds ' boy ' to age, not the sex we want
  8. GG Boy Girl
  9. >>>run (' GG ', sex=' boy ')#混合关键字绑定, can achieve the desired effect
  10. GG Boy

1, If the parameters of a function contains default parameters, then all parameters after this default parameter must be the default parameters ,

otherwise it throws: Syntaxerror:non-default argument follows default argument exception.

Python code
    1. def run (name,age=10,sex):
    2. print name, age, sex
    3. Syntaxerror:non-default argument follows default argument GG

Several exceptions

Python code
  1. def run (name,age,sex=' boy '):
  2. Print Name,age,sex
  3. >>>run ()#required argument missing
  4. >>>run (name=' GG ',23°c)#non-keyword argument following keyword
  5. >>>run (' GG ', name=' pp ')#duplicate value for argument
  6. >>>run (actor=' xxxx ')#unknown keyword
  7. #第一种情况是丢失参数
  8. #第二种情况是: If the first keyword binding is used, the following must use the keyword binding
  9. #第三种情况: You cannot use both location and keyword bindings in a single call
  10. #第四种情况: You cannot use a keyword outside the argument list

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

Python code
    1. >>>i = 5
    2. >>>def f (arg=i):
    3. >>> Print arg
    4. >>>i = 6
    5. >>>f ()
    6. 5 #结果是5

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

Python code
  1. >>> def F (A, l=[]):
  2. >>> L.append (a)
  3. >>> return L
  4. >>> Print F (1)
  5. >>> print F (2)
  6. >>> print F (3)
  7. [1]
  8. [1, 2]
  9. [1, 2, 3]
  10. #可以用另外一种方式实现:
  11. >>> def F (A, l=None):
  12. >>> If L is None:
  13. >>> L = []
  14. >>> L.append (a)
  15. >>> return L

Variable parameters

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

Python code
  1. def run (Name,*args):
  2. print name,' runing '
  3. For A in args: print a
  4. >>> run (' GG ',' mm ')
  5. GG runing
  6. Mm
  7. >>> run (' GG ',1,2,' mm ')
  8. GG runing
  9. 1
  10. 2
  11. Mm
  12. >>> run (' GG ',1,1.02,[' mm ',' GM ')
  13. GG runing
  14. 1
  15. 1.02
  16. [' mm ',' GM ']

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

variable parameters for keyword bindings (**args this form, look at the original document, not very understanding, for the moment called)

Python code
  1. def run (Name,**args):
  2. Keys = Args.keys ()
  3. For K in keys:
  4. Print K,args[k]
  5. >>> run (' Nana ', type=' open ')
  6. Type Open
  7. >>> run (' Nana ', type=' open ', title=' Gogo ')
  8. Type Open
  9. Title Gogo
  10. #*arg must be in front of **args.
  11. def run (Name,*arg,**args):
  12. For A in arg:print a
  13. Keys = Args.keys ()
  14. For K in keys:
  15. Print K,args[k]
  16. >>> run (' nn ',' mm ',1,2,' oo ', type=' open ', title=' Gogo ')
  17. Mm
  18. 1
  19. 2
  20. Oo
  21. Type Open
  22. Title Gogo

Splitting of parameter columns

Python code
    1. >>> range (3, 6)              #  normal call with separate arguments  
    2. [ 3, 4, 5]  
    3. >>> args = [3, 6]  
    4. >>> range (*args)              # call with arguments unpacked from a  list  
    5. [3, 4,  5]  

By using the lambda keyword, you can create short, anonymous functions

Python code
  1. #这个例子没怎么看懂
  2. >>> def make_incrementor (n):
  3. ...  return Lambda x:x + n #相当于创建了一个一x为参数的匿名函数?
  4. ...
  5. >>> f = make_incrementor#f = Make_incrementor (n=42), sets the value of n
  6. >>> f (0)#其实调用的是匿名函数?
  7. 42
  8. >>> f (1)
  9. 43
  10. #看下面一个例子报的错误明白一点了
  11. >>>def t (n):
  12. ... Print X*n
  13. >>>m = t (2)
  14. Traceback (most recent):
  15. File "<pyshell#85>", line 1, in <module>
  16. m = t (2)
  17. File "<pyshell#84>", line 2, in t
  18. Print X*n
  19. Nameerror: Global name ' x ' is not defined
  20. Says no global name ' x ' is defined
  21. >>> x =Ten
  22. >>> def t (n):
  23. ... Print X*n
  24. >>> m = t (2)
  25. 20
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.