python学习笔记二(函数)

#encoding=UTF-8
'''
Created on 2011-5-18

@author: lingyibin
'''

#python函数
def add(a,b):
    return a+b
print add(1,2)
print add("abc","def")

#默认参数
def  myjoin(str,sep=","):
    return sep.join(str)
print myjoin(["a","b","c"])
print myjoin(["a","b","c"],"\t")

#上面的结果:
'''
3
abcdef
a,b,c
a    b    c
'''

#但注意一点,如果一个参数是可以选的话,它后面的参数也必须是可以选的。如下:
'''
def myrange(start = 0,stop,step=1):
    print stop,start,step;
#报错:SyntaxError: non-default argument follows default argument
'''

#tuple,可选参数个数
def printf(format,*arg):
    print type(arg) #SyntaxError: non-default argument follows default argument
    print format%arg #a1
printf("a%d",1)
    
#dectionary,可选参数个数
def printf2(format,**keyword):
    for k in keyword.keys():
        print "keyword[%s] is %s"%(k,keyword[k])
printf2("ok",one=1,two=2,three=3)
'''结果:
keyword[three] is 3
keyword[two] is 2
keyword[one] is 1
'''

#可以自动分辨tuple和dictionary
def testfun(fixed,optional=1,*arg,**keywords):
    print ""
    print "fixed parameters is ",fixed
    print "optional parameter is ",optional
    print "Arbitrary parameter is ", arg
    print "keywords parameter is ",keywords
testfun(1,2,"a","b","c",one=1,two=2,three=3)
'''结果
fixed parameters is  1
optional parameter is  2
Arbitrary parameter is  ('a', 'b', 'c')
keywords parameter is  {'three': 3, 'two': 2, 'one': 1}
'''

'''
每一个函数都是一个对象。
都有一个__doc__属性,它在函数的开头处定义,如要没定义,则默认为空
'''
def myfun():
    """
hello,this is lingyibin
    """
    return 
print myfun.__doc__
'''结果:

hello,this is lingyibin
    
'''

print " ".join.__doc__
print range.__doc__
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值