Python Basics-function (i)--python3

Source: Internet
Author: User

Python Basic---function (i)

Directory Python Basic---functions (i) 1. Definition of function 2. Detailed parameters of functions 3.return4.lambda anonymous functions

1. Definition of functions

function  功能,函数    函数就是对代码进行一个封装,把实现某一功能的相同代码,进行封装到一起。下次需要使用时,就不需要进行代码编写,直接调用即可。好处:    增加代码的复用性,增加代码的可读性减少代码的编写量,降低维护成本。    函数可以看成,解决某类问题的‘工具’定义方法:‘‘‘def function_name(params):    block    return expression(表达式)/value‘‘‘def 关键字表示定义一个函数function_name 函数名,和变量的命名规则相同,以字母和_开头,可以包含字母,数字和_params 表示参数,可以是零个,一个或者多个参数,函数参数不用指定参数类型#examples    def dieDai(iter):        for i in iter:            print(i)    >>> li=(1,2,3,4)    >>> dieDai(li)    1    2    3    4

2. Detailed parameters of the function

1.必备参数:参数没有默认值2.默认参数:参数是有默认值,调用函数是可以传参也可以不传参,不传时,参数是默认值3.不定长参数:可在定义是定义,也可在传入时定义传入    定义方法:def function_name(*args,**kwargs)    *args 将传入参数包装成元祖    **kwargs  将传入参数包装成字典
  • [] #1. Do not pass parameters
    Def fun1 ():
    Print (' cannot pass parameter ')

    >> fun1 (' Q ')
    Traceback (most recent):
    File "<pyshell#7>", line 1, in <module>
    FUN1 (' Q ')
    TYPEERROR:FUN1 () takes 0 positional arguments but 1 was given
    >> fun1 ()
    Cannot pass parameters
    #2. Required Parameters
    Def fun2 (a):
    Print (' must pass parameter: ', a)
    >> fun2 (2)
    Parameters must be passed: 2
    #3. Default parameter parameters can be passed or not
    def fun3 (b=2):
    Print (' Default parameter: ', b)
    >> Fun3 ()
    Default parameter: 2
    >> Fun3 (4)
    Default parameter: 4
    >> Fun3 (b=10)
    Default parameter: 10
    # #4. Optional parameters can be passed 0-multiple, packaging Cheng Yuanju
    Def fun4 (Arg):
    Print (' can wear 0 to multiple ', ARG)
    >> Fun4 () #返回一个空元祖
    Can wear 0 to multiple ()
    >> fun4 (1) #返回一个元祖
    Can wear 0 to multiple (1,)
    >> Fun4 (2,3)
    Can wear 0 to multiple (2, 3)
    >> Fun4 (4,5,6,7,8)
    Can wear 0 to multiple (4, 5, 6, 7, 8)
    >> Fun4 ([up])
    Can wear 0 to multiple ([1, 2],)
    >> fun4 (' SDF ')
    Can wear 0 to multiple (' SDF ',)
    >> fun4 ({' Q ': 123})
    Can wear 0 to multiple ({' Q ': 123},)
    >> Fun4 (())
    Can wear 0 to multiple ((1, 2),)
    #可选参数, when you send a parameter, add
    , remove the inner shell (unpack)
    >> Fun4 (())
    Can wear 0 to multiple (1, 2)
    >> Fun4 (
    {' Q ': 123})
    Can wear 0 to multiple (' Q ',)
    >> Fun4 ([+])
    Can wear 0 to multiple (1, 2)
    >> Fun4 (
    ' SDF ')
    Can wear 0 to multiple (' s ', ' d ', ' F ')
    # #5. Keyword parameters
    Def fun5 (A, b): #定义的时候跟必备参数一样
    Print (A, b) #必须放到最后
    >> Fun5 (a=1,b=2)
    1 2

          def fun6 (**kwarg): print (' keyword parameter: ', Kwarg) #包装成字典 (can pass 0-more) >>> fun6 () keyword parameter: {} &GT;&G T;> fun6 (a=1,b=2) #遵循变量名规则 keyword parameter: {' A ': 1, ' B ': 2} >>> fun6 (**{' a ': 123, ' B ': ' Wer '}) keyword parameter: {        ' A ': 123, ' B ': ' Wer '} >>> fun6 (**{1:123,2: ' Wer '}) #key必须是字符串 Traceback (most recent call last): File "<pyshell#48>", line 1, in <module> fun6 (**{1:123,2: ' Wer '}) typeerror:fun6 () keyword          s must be strings # #参数混合时 keyword parameters must be followed, according to the defined book order, to ensure that the required parameters can get the value and only one #1. Required parameters + default parameters: The default parameter must be the Def fun7 (b,a=1) after the required parameters: Print (b) >>> fun7 (1,) 1 1 >>> fun7 (' Q ', a= ' we ') we Q >>> fun7 (a= ' we ' , b= ' ert ') we ert >>> fun7 (' Q ', ' W ') w q #2 def fun8 (b,m=1,*a): print (b) pri NT (m) print (a) ================== >>> fun8 (1,2,3,4,5,6,7,8) 1 2 (3, 4, 5, 6, 7  , 8) >>> #3 def fun9 (*a,b,m): #b, M key self-parameter print (a,b,m) print (b) print (m) >>> Fun9 ( , 3,4,5,b= ' Q ', m= ' W ') (1, 2, 3, 4, 5) Q W q W

3.return

return 有两个作用:    1.用来返回函数的运行结果,或者调用另外一个函数。比如max()函数    2.函数结束的标志。主要运行了return,就强制结束了函数。return后面的程序都不会执行如果函数中没有写return,其实函数运行结束时,默认执行了 return Nonereturn 语句的位置是可选的,不是固定出现再函数的最后,可以自定义在函数的任何地方。#返回函数的运行结果    >>> def fun1(a,b):      #返回a=2        if a>b:            return a    >>> fun1(2,1)    2    >>> a=fun1(2,1)    >>> a    2    >>> def fun1(a,b):      #返回b=None        if a>b:            print(a)    >>> fun1(2,1)    2    >>> b=fun1(2,1)    2    >>> b#函数结束的标志 可以放在任何地方    >>> def fun10(a,b):        if a>b:            print(a)    >>> fun10(2,1)    2    >>> def fun10(a,b):        return(‘我不下去了‘) #函数结束标志        if a>b:            print(a)    >>> fun10(2,1)    ‘我不下去了‘

4.lambda Anonymous functions

没有函数名的函数g = lamdba x:x+1lambda 简化了函数定义的书写形式。是代码更为简洁,但是使用函数的定义方式更为直观,易理解lambda的应用场景:1.有些函数如果只是临时一用,而且它的业务逻辑也很简单时,就没有必要用def来定义,这个时候就可以使用lambda。2.函数都支持函数作为参数。lambda函数就可以应用>>> fun10           #函数体<function fun10 at 0x0000000003429D08>>>> g=lambda x:x+1  #函数体>>> g<function <lambda> at 0x00000000034371E0>>>> g(1)2

Python Basics-function (i)--python3

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.