1#方法的参数定义和默认参数的定义2defask_ok(PRompt, retries=4, complaint='Yes or no, please!'):3whileTrue:4ok =input(prompt)5ifokin('y','ye','yes'):6print("true");7ifokin('n','no','nop','nope'):8returnFalse9retries = retries - 110ifretries <0:11raiseOSError('uncoOperative user');#相当于c#中的throw;12print(complaint)1314#方法的调用15defshow():16ask_ok("please input docstring");171819#默认值的共享20deffun(n,args=[]):21args.append(n);22returnargs;2324print(fun(2));25print(fun(3));#长度加126print(fun(4));#长度加127282930#除去默认值的累计,->为注释,表示方法的返回值类型31deffunc(n,args=None)->[]:32ifargsisNone:33args=[];34args.append(n);35returnargs;3637print(func(2));38print(func(3));#长度139print(func(4));#长度14041424344#*当最后一个形参以 **name 形式出现,它接收一个字典 (见映射类型 —— 字典) ,该字典包含了所有未出现在形式参数列表中的关键字参数。45#它还可能与 *name 形式的参数(在下一小节中所述)组合使用,*name 接收一个包含所有没有出现在形式参数列表中的位置参数元组。46#(*name 必须出现在 ** name 之前。)例如,如果我们定义这样的函数:4748defgetInfo(info,*argument,**keyWords):49print("this is",info);50formsginargument:51print(msg);52forkwinkeywords:53print(kw,":",keywords[kw]);5455getInfo("Limburger","It's very runny, sir.",56"It's really very, VERY runny, sir.",57shopkeeper="Michael Palin",58client="John Cleese",59sketch="Cheese Shop Sketch");6061#参数的分拆62defparrot(name="xiaoxiao",age=24):63print("my name is",name,end='');64print("and my age is",age,end='');6566student={"name":"jack","age":25};67parrot(**student);6869stu=["jack",25];70parrot(*stu);7172#pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]73#pairs.sort(key=lambda pair: pair[1])7475#lamda表达式的使用,就是逆名函数76defsorter(L=None):77ifLisNone:78L=[];79L.sort(key=lambdapair:pair[1]);80returnL;8182L = [(1,'one'), (2,'two'), (3,'three'), (4,'four')];83print(sorter(L));8485#文档字符串86defmyfunction():87"""Do nothing,,,but88No,really,,,it doesn't89""";90pass;9192print(myfunction.__doc__);