天天看點

python函數

1.函數一般形式

  函數代碼塊以 def 關鍵詞開頭,後接函數辨別符名稱和圓括号()。任何傳入參數和自變量必須放在圓括号中間。圓括号之間可以用于定義參數。函數的第一行語句可以選擇性地使用文檔字元串—用于存放函數說明。函數内容以冒号起始,并且縮進。

return [表達式] 結束函數,選擇性地傳回一個值給調用方。不帶表達式的return相當于傳回 None。

例子:

def sum(x,y):

   print("x={0}".format(x))

   print("y={0}".format(y))

   return x+y

m = sum(10,20)

print(m)

2.函數參數

1)函數變量存在預設值時,調用時,優先取新傳入的值

def funcA(x,y=1):

   print x

   print y

funcA(2)

print("*"*20)

funcA(2,2)

結果:

2

1

********************

2)在Python裡,帶*的參數就是用來接受可變數量參數的,參數為tuple,即元組,*c表示3、4、5、6;後面的*test是解包,一一對應關系

def funcA(a,b,*c):

   print(a)

   print(b)

   print("The lenth of c is: %d" % len(c))

   print(c)

funcA(1,2,3,4,5)

d = ('hello,','world')

funcA(1,2,*d)

The lenth of c is: 3

(3, 4, 5)

The lenth of c is: 2

('hello,', 'world')

3)如果一個函數定義中的最後一個形參有 ** (雙星号)字首,所有正常形參之外的其他的關鍵字參數都将被放置在一個字典中傳遞給函數,**b表示字典

def funcB(a,**b):

   for x in b:

       print( x + ":" + str(b[x]))

funcB(1,x="hello,",y="world")

{'y': 'world', 'x': 'hello,'}

y:world

x:hello,

本文轉自 huangzp168 51CTO部落格,原文連結:http://blog.51cto.com/huangzp/1978206,如需轉載請自行聯系原作者