Python function basics

Source: Internet
Author: User

1. Definition and invocation of functions

In [173]: def add (x, y): ...: print (x+y) ...: return x + y ...: in [174]: Add (3,5) 8out[174]: 8


2. Parameters of the function

In [177]: def add (x, y):      ...:     ret  = x + y     ...:     print (' {} +  {} = {} '. Format (x,y,ret))      ...:      return ret     ...:           ...:  in [178]: add (3,5)    #参数按照定义的顺序传入, such a method of communication is called positional parameters 3 + 5 = 8out[ 178]: 8in [179]: in [179]: add (y=3,x=5)   #参数按照定义时的变量名传递, such a parameter method is called the keyword argument 5 +  3 = 8out[179]: 8in [181]: def inc (base,x=1):      #x =1 is the default value parameter      ...:     return base + x      ...: in [182]: inc (3) out[182]: 4in [183]: inc (3,2) Out[183]: 5 variable parameter in [184]: def sum (*LST):      ...:     print (Type (LST))      ...:     ret = 0      ...:     for x in lst:     ...:          ret += x     ...:      return ret     ...: #*lst    add an asterisk before the parameter , which means that the parameter is mutable, that is, it can accept any number of arguments, which will form a tuple, which can only be passed by positional parameters      in [185]: sum <class  ' tuple ' >out[185]: 6in [186]: def connect (**kwargs):      ...:     print (Type (Kwargs))      ...:      for k,v in kwargs.items ():     ...:        &Nbsp; print (' {} => {} '. Format (k,v))      ...:    The       #**kwargs   parameter is preceded by two asterisks, indicating that the parameter is variable and can accept any number of arguments, which form a dictionary, You can only pass the keyword parameter in [187]: connect (host= ' 127.0.0.1 ', port=3306) <class  ' dict ' >port =>  3306host => 127.0.0.1 variable parameter: Position variable parameter  :  parameter name with an asterisk,  form a tuple,  A parameter can only be:  with a parameter name in the form of a positional argument, plus two signals before parameter names,  form a dictionary,  parameters can only be in [190]: def fn in the form of a keyword parameter (x,y,*args,** Kwargs):      ...:     print (x)       ...:      print (y)      ...:      Print (args)      ...:     print (Kwargs)     &NBSP;&NBSP;...:&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;IN&NBSP;[191]:&NBSP;FN (1,2,3,4,5,a=1,b=2) (3, 4, 5) {' A ': 1,  ' B ':  2} usually: the default parameter after the variable parameter after the default parameterand mutable parameters do not appear at the same time 


3. Parametric deconstruction

In [192]: def add (x, y):      ...:     ret  =  x + y     ...:     print (' {}  + {} = {} '. Format (x,y,ret))      ...:      return ret     ...: in [193]: add (1 + 2 ) = 3out[193]: 3in [194]: t = 1,2in [195]: tout[195]:  (1,&NBSP;2) in  [196]: add (T[0],t[1]) 1 + 2 = 3out[196]: 3in [197]: in [197] :  add (*t) 1 + 2 = 3out[197]: 3#*t  positional parameter deconstruction, plus an asterisk, can be the solution of an iterative object to form a positional parameter in [198]:  add (*range (2)) 0 + 1 = 1out[198]: 1in [199]: in [199]: d  = {' x ': 1, ' Y ': 2}in [200]: add (**d) 1 + 2 = 3out[200]: 3#**d  Keyword parameter deconstruction, add two asterisk, you can make the dictionary to form the keyword parameterTwo forms of parametric deconstruction an asterisk   deconstructed object: The result of an iterative object   deconstruction: Positional parameters two asterisks   deconstructed objects: Dictionary   Deconstruction results: keyword parameter keyword-only parameter in [201]: &NBSP;DEF&NBSP;FN (*,y):      ...:     print (y)    The parameters after the    ...:     #*  asterisk can only be passed through the keyword parameter, keyword-only parameter in [202]: &NBSP;FN (y=3) 3

4. Scope of parameters

In [203]: DEF fn (): ...: x = 1 ...: print (x) ...: def inner (): ...: print (x) ...: Inner () ...: in [204]: FN () 11# ancestor scope is visible to subordinates


5. Anonymous function

In [208]: Lambda x:x+1out[208]: <function __main__.<lambda>>in [209]: (Lambda x:x+1) (3) out[209]: 4In [210]: f = Lambda x:x+2in [211]: F (2) out[211]: 4lambda to define the parameter list does not need to use parentheses the colon is not used to open a new statement block without return, the value of the last expression is the return value

6. Generator

In [212]: def g ():      ...:     for x  in range (Ten):     ...:          yield x    #yield表示弹出一个值      ...:          in [213]: r = g ()    #函数已经执行完成, the function of the scene should have been destroyed, but in fact, The function of the scene has not been destroyed in [214]: rout[214]: <generator object g at 0x7f3d60330938 >in [215]: next (R) Out[215]: 0in [216]: next (r) out[216]: 1in [217]:  Next (R) Out[217]: 2in [218]: def gen ():     ...:      print (' a ')      ...:     yield 1      ...:     print (' B ')      ...:      yield 2     ...:     return 3      ...:  in [219]: g = gen ()   #执行生成器函数的时候, function body is not executed in [220]: next (g)  # Execute to first yield, stop execution aout[220]: 1in [221]: next (g)    #从第一个yield之后开始执行,  When the second yield is stopped bout[221]: 2 the function with the yield statement is called the generator function,  The return value of the generator function is the generator generator function execution, when the function body is not executed when the next generator,  The current code executes to the first yield after, the value pops up, and the pause function when the next generator again, from the time of the last pause to execute when there is no extra yield, the stopiteration exception is thrown, the exception value is the function's return value in  [226]: def counter ():      ...:     x =  0     ...:     while True:      ...:         x += 1     &NBSP;...:&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;YIELD&NBSP;X&NBSP;&NBSP;&NBSP;&NBSP;&NBSP, .....:       &nBsp;  in [227]: def inc (c):     ...:      return next (c)      ...: in [228]: c = counter () in  [229]: inc (c) out[229]: 1in [230]: inc (c) out[230]: 2in [231]: d =  counter () In [232]: next (d) out[232]: 1in [233]: next (d) Out[233]: 2In [ 234]: next (d) out[234]: 3in [242]: def make_inc ():      ...:      def counter ():     ...:          x = 0     ...:          while True:     ...:              x += 1     ...:              yield x     ...:      c = counter ()      ...:     return  lambda: next (c)      ...:           ...:          ...: in [243]: incr  = make_inc () in [244]: incrout[244]: <function __main__.make_inc.<locals &GT;.&LT;LAMBDA&GT;&GT;IN&NBSP;[245]:&NBSP;INCR () out[245]: 1in [246]: incr () Out[246]: 2


This article from "Thick tak" blog, declined reprint!

Python function basics

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.