函数参数
Posted mike.liu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了函数参数相关的知识,希望对你有一定的参考价值。
格式:
1.def show():
print("函数参数")
ret = show()
______________________________________________________________________________________________________________________
2.def show(a1,a2,a3=100)#a3为默认参数,默认参数只能放在形式参数后面
print(a1,a2,a3)
show(111,888)
返回(111,888,100)
______________________________________________________________________________________________________________________
3.指定参数
def show(a1,a2)
print(a1,a2)
show(a2=50,a1=30)
返回(30,50)
______________________________________________________________________________________________________________________
4.动态参数
def show(*arg):#一个*把所有的参数转化为一个元祖
print(arg,type(arg))
show(1,2,3,4)
返回(1,2,3,4), class(tuple))
_____________________________________________________________________________________________________________________
5.def show(**arg):#两个*把所有的参数转化为一个字典
print(arg,type(arg))
show(k1=12,k2=21)
返回({k1:12,k2:21}), class(dict))
_____________________________________________________________________________________________________________________
6.def show(*args,**kwargs):#返回相应的模式,一个*的放在前面,两个*放后面,顺序不能颠倒
print(args,type(args)
print(kwargs,type(kwargs))
show(1,2,3,n1=18,n2=‘lgs‘)#传参数时也按顺序
返回
((1, 2, 3), <type ‘tuple‘>)
({‘n1‘: 18, ‘n2‘: ‘lgs‘}, <type ‘dict‘>)
____________________________________________________________________________________________________________________
7.def show(*args,**kwargs):
print(*argw,type(args))
print(**kwargs,type(kwargs))
l=[1,2,3,4]
d=(‘n1‘=2,‘n2‘:‘lgs‘
show(*l,**d)#必须指定*或**
返回
((1, 2, 3, 4), <type ‘tuple‘>)
({‘n1‘: 2, ‘n2‘: 4}, <type ‘dict‘>)
____________________________________________________________________________________________________________________
8.字符串格式化
li = "{0}is{1}"
res = li.format(‘lgs‘,‘studypython‘)
print(res)
返回:lgsisstudypython
______________________________________________________________________________________________________________________
9.字符串格式化
li = "{0}is{1}"
l = [‘lgs‘,‘studypython‘]
res = li.format(*l)
print(res)
返回:lgsisstudypython
______________________________________________________________________________________________________________________
10.字符串格式化
li = "{name} is {acto‘}"
d = {‘name‘:‘mike‘,‘actor‘:‘stu‘}
res = li.format(**d)
print(res)
返回
mike is stu
以上是关于函数参数的主要内容,如果未能解决你的问题,请参考以下文章