python 定义函数_python 定义函数

python定义函数:在Python中,可以定义包含若干参数的函数,这里有几种可用的形式,也可以混合使用:1.默认参数最常用的一种形式是为一个或多个参数指定默认值。>>>defask_ok(prompt,retries=4,complaint='YesornoPlease!'):whileTrue:ok=input(prompt)ifokin('y','ye','yes'):returnTrueifokin('n','no','nop','nope'):returnFalseretries=retries-1ifretries<0:raiseIOError('refusenikuser')print(complaint)这个函数可以通过几种方式调用:只提供强制参数>>>ask_ok('Doyoureallywanttoquit?')Doyoureallywanttoquit?yesTrue提供一个可选参数>>>ask_ok('OKtooverwritethefile',2)OKtooverwritethefileNoYesornoPlease!OKtooverwritethefilenoFalse提供所有的参数>>>ask_ok('OKtooverwritethefile?',2,'Comeon,onlyyesorno!')OKtooverwritethefile?testComeon,onlyyesorno!OKtooverwritethefile?yesTrue2.关键字参数函数同样可以使用keyword=value形式通过关键字参数调用>>>defparrot(voltage,state='astiff',action='voom',type='NorwegianBlue'):print("--Thisparrotwouldn't",action,end='')print("ifyouput",voltage,"voltsthroughit.")print("--Lovelyplumage,the",type)print("--It's",state,"!")>>>parrot(1000)--Thisparrotwouldn'tvoomifyouput1000voltsthroughit.--Lovelyplumage,theNorwegianBlue--It'sastiff!>>>parrot(action="vooooom",voltage=1000000)--Thisparrotwouldn'tvooooomifyouput1000000voltsthroughit.--Lovelyplumage,theNorwegianBlue--It'sastiff!>>>parrot('athousand',state='pushingupthedaisies')--Thisparrotwouldn'tvoomifyouputathousandvoltsthroughit.--Lovelyplumage,theNorwegianBlue--It'spushingupthedaisies!但是以下的调用方式是错误的:>>>parrot(voltage=5,'dead')SyntaxError:non-keywordargafterkeywordarg>>>parrot()Traceback(mostrecentcalllast):File"<pyshell#57>",line1,in<module>parrot()TypeError:parrot()missing1requiredpositionalargument:'voltage'>>>parrot(110,voltage=220)Traceback(mostrecentcalllast):File"<pyshell#58>",line1,in<module>parrot(110,voltage=220)TypeError:parrot()gotmultiplevaluesforargument'voltage'>>>parrot(actor='John')Traceback(mostrecentcalllast):File"<pyshell#59>",line1,in<module>parrot(actor='John')TypeError:parrot()gotanunexpectedkeywordargument'actor'>>>parrot(voltage=100,action='voom',action='voooooom')SyntaxError:keywordargumentrepeatedPython的函数定义中有两种特殊的情况,即出现*,**的形式。*用来传递任意个无名字参数,这些参数会以一个元组的形式访问**用来传递任意个有名字的参数,这些参数用字典来访问(*name必须出现在**name之前)>>>defcheeseshop1(kind,*arguments,**keywords):print("--Doyouhaveany",kind,"?")print("--I'msorry,we'realloutof",kind)forarginarguments:print(arg)print("-"*40)keys=sorted(keywords.keys())forkwinkeys:print(kw,":",keywords[kw])>>>cheeseshop1("Limbuger","It'sveryrunny,sir.","It'sreallyvery,veryrunny,sir.",shopkeeper="M

ichaelPalin",client="John",sketch="CheeseShopSketch")--DoyouhaveanyLimbuger?--I'msorry,we'realloutofLimbugerIt'sveryrunny,sir.It'sreallyvery,veryrunny,sir.----------------------------------------client:Johnshopkeeper:MichaelPalinsketch:CheeseShopSketch>>>3.可变参数列表最常用的选择是指明一个函数可以使用任意数目的参数调用。这些参数被包装进一个元组,在可变数目的参数前,可以有零个或多个普通的参数通常,这些可变的参数在形参列表的最后定义,因为他们会收集传递给函数的所有剩下的输入参数。任何出现在*args参数之后的形参只能是“关键字参数”>>>defcontact(*args,sep='/'):returnsep.join(args)>>>contact("earth","mars","venus")'earth/mars/venus'4.拆分参数列表当参数是一个列表或元组,但函数需要分开的位置参数时,就需要拆分参数调用函数时使用*操作符将参数从列表或元组中拆分出来>>>list(range(3,6))[3,4,5]>>>args=[3,6]>>>list(range(*args))[3,4,5]>>>以此类推,字典可以使用**操作符拆分成关键字参数>>>defparrot(voltage,state='astiff',action='voom'):print("--Thisparrotwouldn't",action,end='')print("ifyouput",voltage,"voltsthroughit.",end='')print("E's",state,"!")>>>d={"voltage":"fourmillion","state":"bleedin'demised","action":"VOOM"}>>>parrot(**d)--Thisparrotwouldn'tVOOMifyouputfourmillionvoltsthroughit.E'sbleedin'demised!5.Lambda在Python中使用lambda来创建匿名函数,而用def创建的是有名称的。pythonlambda会创建一个函数对象,但不会把这个函数对象赋给一个标识符,而def则会把函数对象赋值给一个变量pythonlambda它只是一个表达式,而def则是一个语句>>>defmake_incrementor(n):returnlambdax:x+n>>>f=make_incrementor(42)>>>f(0)42>>>f(2)44>>>g=lambdax:x*2>>>print(g(3))6>>>m=lambdax,y,z:(x-y)*z>>>print(m(3,1,2))46.文档字符串关于文档字符串内容和格式的约定:第一行应该总是关于对象用途的摘要,以大写字母开头,并且以句号结束如果文档字符串包含多行,第二行应该是空行>>>defmy_function():"""Donothing,butdocumentit.No,really,itdoesn'tdoanything."""pass>>>print(my_function.__doc__)Donothing,butdocumentit.No,really,itdoesn'tdoanything.

阅读全文 >

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值