[ ] #1.不傳參數
def fun1():
print(‘不能傳參數‘)
>> fun1(‘q‘)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
fun1(‘q‘)
TypeError: fun1() takes 0 positional arguments but 1 was given
>> fun1()
不能傳參數
#2.必備參數
def fun2(a):
print(‘必須傳參數:‘,a)
>> fun2(2)
必須傳參數: 2
#3.預設參數 參數可傳也可不傳
def fun3(b=2):
print(‘預設參數:‘,b)
>> fun3()
預設參數: 2
>> fun3(4)
預設參數: 4
>> fun3(b=10)
預設參數: 10
##4.選擇性參數 可傳0-多個,封裝成元祖
def fun4(arg):
print(‘可以穿0個到多個‘,arg)
>> fun4() #返回一個空元祖
可以穿0個到多個 ()
>> fun4(1) #返回一個元祖
可以穿0個到多個 (1,)
>> fun4(2,3)
可以穿0個到多個 (2, 3)
>> fun4(4,5,6,7,8)
可以穿0個到多個 (4, 5, 6, 7, 8)
>> fun4([1,2])
可以穿0個到多個 ([1, 2],)
>> fun4(‘sdf‘)
可以穿0個到多個 (‘sdf‘,)
>> fun4({‘q‘:123})
可以穿0個到多個 ({‘q‘: 123},)
>> fun4((1,2))
可以穿0個到多個 ((1, 2),)
#選擇性參數,傳參時加號,就把裡面的殼去掉(解包)
>> fun4((1,2))
可以穿0個到多個 (1, 2)
>> fun4({‘q‘:123})
可以穿0個到多個 (‘q‘,)
>> fun4([1,2])
可以穿0個到多個 (1, 2)
>> fun4(‘sdf‘)
可以穿0個到多個 (‘s‘, ‘d‘, ‘f‘)
##5.關鍵字參數
def fun5(a,b): #定義的時候跟必備參數一樣
print(a,b) #必須放到最後
>> fun5(a=1,b=2)
1 2
def fun6(**kwarg): print(‘關鍵字參數:‘,kwarg) #封裝成字典(可傳0-多個) >>> fun6() 關鍵字參數: {} >>> fun6(a=1,b=2) #遵循變數名規則 關鍵字參數: {‘a‘: 1, ‘b‘: 2} >>> fun6(**{‘a‘:123,‘b‘:‘wer‘}) 關鍵字參數: {‘a‘: 123, ‘b‘: ‘wer‘} >>> fun6(**{1:123,2:‘wer‘}) #key必須是字串 Traceback (most recent call last): File "<pyshell#48>", line 1, in <module> fun6(**{1:123,2:‘wer‘}) TypeError: fun6() keywords must be strings ##參數混合時 關鍵字參數必須在後面,根據定義的書序,確保必備參數能拿到值且只有一個 #1.必備參數+預設參數:預設參數必須在必備參數的後面 def fun7(b,a=1): print(a,b) >>> fun7(1,) 1 1 >>> fun7(‘q‘,a=‘we‘) we q >>> fun7(a=‘we‘,b=‘ert‘) we ert >>> fun7(‘q‘,‘w‘) w q #2 def fun8(b,m=1,*a): print(b) print(m) print(a) ================== >>> fun8(1,2,3,4,5,6,7,8) 1 2 (3, 4, 5, 6, 7, 8) >>> #3 def fun9(*a,b,m): #b,m為關鍵自參數 print(a,b,m) print(b) print(m) >>> fun9(1,2,3,4,5,b=‘q‘,m=‘w‘) (1, 2, 3, 4, 5) q w q w