1. 程式人生 > >python 基礎 4.0 函數的一般形式及傳參

python 基礎 4.0 函數的一般形式及傳參

hit lin style 參數 odi 你好 value weight 入參

#/usr/bin/python #coding=utf-8 #@Time :2017/10/23 15:58 #@Auther :liuzhenchuan #@File :函數的一般形式.py ##函數的定義 #x y 為形參 ,sum(6,4)叫實參 def sum(x,y): print {‘x = 0‘.format(x)} print {‘y = 0‘.format(y)} return x + y m = sum(6,4) print m >>> set([‘x = 0‘]) set([‘y = 0‘]) 10 ###函數的參數
#給形參b定義一個默認的值 def funcA(a,b=0): print a print b funcA(1) >>> 1 0 #如果實參傳入的時候,判定了b的值,那麽b優先選擇傳入的實參,當b沒有值時,才會選擇默認的值 def funcA(a,b=0): print a print b funcA(10,30) >>> 10 30 ##參數為tuple #a對應1,b對應2,*c對應剩下的元組列型 def funcD(a,b,*c): print a print b print ‘length of c is :%d‘ % len(c)
print c funcD(1,2,3,4,5,6) >>> 10 1 2 length of c is :4 (3, 4, 5, 6) #通過解包的形式傳入元組 def funcD(a,b,*c): print a print b print ‘length of c is :%d‘ % len(c) print c # funcD(1,2,3,4,5,6) #通過解包的形式傳入元組 test = (‘hello‘,‘world‘) funcD(1,2,*test) >>> 1 2 length of c is :2
(‘hello‘, ‘world‘) ##傳入參數為字典,兩個星號b代表的是字典,x是字典的鍵值,b[x]是字典的value.100是a的實參;x=‘hello‘,y=‘nihao‘ 是b的實參,是給a和b賦值 所以不能寫成 a=‘hello‘,b=‘nihao‘,也就是不能再用a和b當作實參。 def funcF(a,**b): print a print b for x in b: print x + ":" + str(b[x]) funcF(100,x=‘hello‘,y=‘nihao‘) >>> {‘y‘: ‘nihao‘, ‘x‘: ‘hello‘} y:你好 x:hello #還可以通過解包的形式,傳入字典 def funcF(a,**b): print a print b for x in b: print x + ":" + str(b[x]) # funcF(100,x=‘hello‘,y=‘你好‘) #還可以通過解包的形式傳入字典 args = {‘1‘:‘a‘,‘2‘:‘b‘} funcF(100,**args) >>> {‘1‘: ‘a‘, ‘2‘: ‘b‘} 1:a 2:b

python 基礎 4.0 函數的一般形式及傳參