python函数的基本使用与参数

来源:互联网 发布:mac上怎样打开pdf文件 编辑:程序博客网 时间:2024/05/18 06:21

函数的定义格式

#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 bfuncA(1)funcA(10,20)

1
0
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)

1
2
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}#将字典当成参数传入的时候需要进行解包动作,即**argsfuncF(200,**args)

100
y:word
x:hello
200
aa:1
bb:2

原创粉丝点击