Python不定参数自定义函数

来源:互联网 发布:mysql修改字符集命令 编辑:程序博客网 时间:2024/06/06 10:00
<span style="font-size:14px;"># -*- coding: gbk -*-#python进阶探究a,b = 0,1while b < 100:    print str(b)+',',    a,b = b,a+bprint("-"*40)    if b == 10:    pass #这句话什么都不做#定义一个方法def fib(n):    a,b = 0,1    while b < n:        print(str(b),',')        a,b = b,a+bfib(2000)print("-"*40)#函数可以直接指定f = fibf(100)print("-"*40)#不定长参数'''python提供了两种特别的方法来定义函数的参数:1. 位置参数 *args,  把参数收集到一个元组中,作为变量args  def show_args(*args):   =>  how_args("hello", "world")2. 关键字参数 **kwargs, 是一个正常的python字典类型,包含参数名和值  def show_kwargs(**args):  = > show_kwargs(foo="bar", spam="eggs")'''def cheeseshop(kind,*arguments,**keywords):    print("-- Do you have any", kind, "?")    print(r"-- I’m sorry, we’re all out of", kind)    for arg in arguments:        print(arg)    print("-"*40)    keys = sorted(keywords.keys())    for kw in keys:        print(kw, ":", keywords[kw])cheeseshop("Limburger", "It’s very runny, sir.","It’s really very, VERY runny, sir.",shopkeeper="Michael Palin",client="John Cleese",sketch="Cheese Shop Sketch")print("-"*40)#字典可以用** 操作符实现关键字参数def parrot(voltage, state='a stiff', action='voom'):     print("-- This parrot wouldn’t", action)     print("if you put", voltage, "volts through it.")     print("E's", state, "!")d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}parrot(**d)#3.2.3才支持此种写法'''def concat(*args,sep="/"):    return sep.join(args)concat("earth", "mars", "venus")concat("earth", "mars", "venus", sep=".")print("-"*40)'''</span>

0 0
原创粉丝点击