1 #一個參數, 2 def show(arg): 3 print(arg) 4 show("kkkkk") #參數能夠是列表,字典等,只要是一個元素就行 5 6 #兩個參數 7 def show(agr,xxx): 8 print(agr,xxx) 9 show("hhhh",77777) #若是隻寫一個參數會報錯 10 11 #默認參數,默認參數必須放在後面,即不能放在首位 12 def show(a1,a2=999): 13 print(a1,a2) 14 show(111) #默認參數,在執行函數時,參數能夠不小寫(執行結果會把默認的值輸出) 15 show(111,888) 16 17 #指定參數 18 def show(a3,a4): 19 print(a3,a4) 20 show(a4=123,a3=999) #這樣就會不按照順序執行了 21 22 #執行結果: 23 kkkkk 24 hhhh 77777 25 111 999 26 111 888 27 999 123
2、動態參數:函數
1 #1.形參加一個星號,輸出爲元組 2 def show(*arg): 3 print(arg,type(arg)) 4 show(11,22,33,44,55,66) #加一個星號的參數,輸出結果把實際參數都放進了一個元組裏了 5 6 #執行結果: 7 (11, 22, 33, 44, 55, 66) <class 'tuple'>
1 2.形參加兩個星號,輸出爲字典 2 def show(**arg): 3 print(arg,type(arg)) #加兩個星號的參數,輸出結果把實際參數都放進了一個字典裏了 4 show(n1=78,uu=123,bb=999) #實際參數書寫格式,按照字典寫法 5 6 #執行結果: 7 {'n1': 78, 'uu': 123, 'bb': 999} <class 'dict'>
1 #3.聯合使用,必須先元組後字典 2 def show(*args,**kwargs): #聯合使用,形參也必須先寫一個星的,後面才寫兩個星的參數 3 print(args,type(args)) 4 print(kwargs,type(kwargs)) 5 show(11,22,33,44,aa="sdf",bb="456") #聯合使用時,要求前面寫一個星的,後面寫兩個星的,不然會報錯 6 7 #執行結果: 8 (11, 22, 33, 44) <class 'tuple'> 9 {'aa': 'sdf', 'bb': '456'} <class 'dict'>
1 #4.若是實際參數用賦了值的變量,會把變量當成元素放到元組 2 #想要原格式輸出,則需在變量前相應加1個星號或者2個星號 3 def show(*args,**kwargs): #聯合使用,形參也必須先寫一個星的,後面才寫兩個星的參數 4 print(args,type(args)) 5 print(kwargs,type(kwargs)) 6 # show(11,22,33,44,aa="sdf",bb="456") #聯合使用時,要求前面寫一個星的,後面寫兩個星的,不然會報錯 7 li = [11,22,33,44,55] 8 dic = {"n1":44,"n2":"dsf"} 9 show(li,dic) #把li和dic當作2個元素放到元組了,字典爲空 10 show(*li,**dic) #若是想把值按原格式輸出,則相對應的加一個星或者加2個星 11 12 #執行結果: 13 ([11, 22, 33, 44, 55], {'n1': 44, 'n2': 'dsf'}) <class 'tuple'> 14 {} <class 'dict'> 15 (11, 22, 33, 44, 55) <class 'tuple'> 16 {'n1': 44, 'n2': 'dsf'} <class 'dict'>
應用:spa
1 # 2 s1 = "{0} is {1}" 3 result = s1.format("yaom","345") #正常的字符串格式化賦值 4 print(result) 5 6 s1 = "{0} is {1}" 7 li = ["yao","345"] 8 result = s1.format(*li) #利用列表轉換輸出 9 print(result) 10 11 s1 = "{name} is {acter}" 12 result = s1.format(name="liug",acter="sbt") #正常的字符串格式賦值 13 print(result) 14 15 s1 = "{name} is {acter}" 16 dic = {"name":"liu","acter":"sbt"} # 17 result = s1.format(**dic) #利用字典轉換輸出 18 print(result) 19 20 #執行結果: 21 yaom is 345 22 yao is 345 23 liug is sbt 24 liu is sbt
1 #lambda表達式,簡單函數表達式 2 def func(a): 3 b = a+1 4 return b 5 result = func(4) 6 print(result) 7 #lambda表達式,簡單函數的簡單表示(和li = []與li = list()表達同樣) 8 func = lambda a:a+1 #只用一行就表示出來了,不用跳行 9 #建立形式參數a 10 #函數內容,a+1 並把結果return 11 ret = func(99) 12 print(ret) 13 14 #執行結果: 15 5 16 100