python的函数

来源:互联网 发布:法国房补 知乎 编辑:程序博客网 时间:2024/06/05 12:34

函数的定义格式


#x,y是形参,代表形象参数
def sum(x,y):
    print ('x={0}'.format(x))
    print ('x={0}'.format(y))
    return x+y
#这里的10,3是实参,代表实际参数
#调用sum(x,y)这个函数
m = sum(10,3)
print(m)
x=10 
x=3 
13
函数的参数


#给b设置一个默认值,不赋值就用默认
#如果实参传入的时候,b指定了值时,优先使用传入参数,b没值时才用默认
def funcA(a,b=0):
    print a
    print b
funcA(1)
funcA(10,20)


10 
20
#参数为tuple,其中*c代表一个元组
def funcD(a,b,*c):
    print a
    print b
    print "length of c %d" %len(c)
    print c
#其中3,4,5,6作为了一个元组传入
funcD(1,2,3,4,5,6)


length of c 4 
(3, 4, 5, 6)
#传入参数为dict,其中**b代表字典
def funcF(a,**b):
    print a
    for x in b:
        print x+':'+str(b[x])


funcF(100,x='hello',y='word')
args={'aa':1,'bb':2}
#将字典当成参数传入的时候需要进行解包动作,即**args
funcF(200,**args)
100 
y:word 
x:hello 
200 
aa:1 
bb:2

原创粉丝点击