Python_函數_參數

來源:互聯網
上載者:User

標籤:插入   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_函數_參數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.