標籤:插入 tuple 技術分享 col strong 函數返回 傳參 lov 列表
def 是函數的關鍵字,Python解譯器一旦執行到def,預設不執行
def li(): n = 8 n +=1 print(n)
li()li2 = lili2()
結果:
99
return():用於函數傳回值,用於中斷函數操作
參數可以是數字,字串,列表,元組,字典
預設參數:預設參數Python規定放在普通參數後面
def li(a1,a2=11) print(a1,a2)
li(111)li(111,222)
結果:
111 11111 222
指定參數:指定後按指定參數的順序執行
def li(a1,a2) print(a1,a2)
li(a2=32,a1=8)
結果:
8 32
動態參數:
預設元組:
def show(*arg): print(arg,type(arg))
show(33)show(11,33,66,44,66)
結果:
(33,) <class ‘tuple‘>(11, 33, 66, 44, 66) <class ‘tuple‘>
預設字典:
def show(**arg): print(arg, type(arg))
show( n1=123, n2= ‘hello‘,n3=5,)
結果:
{‘n1‘: 123, ‘n2‘: ‘hello‘, ‘n3‘: 5} <class ‘dict‘>
預設先插入元組,再插入字典:
def show(*args, **kwargs): print(args, type(args)) print(kwargs, type(kwargs))show(11, 22, 44, 55, n1=88, n2=‘presly‘)
l = [11, 22, 44, 55,]
d = {‘n1‘: 123, ‘n2‘: ‘hello‘}
show(l, d)
show(*l,**d)
結果:
(11, 22, 44, 55) <class ‘tuple‘>{‘n1‘: 88, ‘n2‘: ‘presly‘} <class ‘dict‘>([11, 22, 44, 55], {‘n1‘: 123, ‘n2‘: ‘hello‘}) <class ‘tuple‘>{} <class ‘dict‘>(11, 22, 44, 55) <class ‘tuple‘>{‘n1‘: 123, ‘n2‘: ‘hello‘} <class ‘dict‘>
動態參數實現 字串格式化:
例:
# s1 = ‘{0} is {1}‘ # *args的傳參# l = [‘Presly‘, ‘lovely‘]# # result = s1.format(‘Presly‘, ‘lovely‘)# result = s1.format(*l)# print(result)s1 = ‘{name} is {acter}‘ # **kwargs的傳參d = {‘name‘: ‘Presly‘, ‘acter‘: ‘lovely‘}result = s1.format(**d)print(result)
結果:
Presly is lovely
Python_函數_參數