1.函數的一般形式
定義一個函數需要以下規則:
函數代碼塊以 def 關鍵詞開頭,後接函數標識符名稱和圓括號()
任何傳入參數和自變量必須放在圓括號中間,圓括號中間可以用於自定義參數。
函數的第一行語句可以選擇性的使用文檔字符串-用於存放函數說明
函數內容以冒號起始,並且縮進
return[表達式] 表示函數結束,不帶表達式的return,返回None
創建一個函數:
def fun(x,y):
print ('x = {0}'.format(x))
print ('y = {0}'.format(y))
return x+y
x =1
y =3
z = fun(x,y)
print z
返回爲:
x = 1
y = 3
4
def是函數的關鍵字,函數的格式
def 後面就是函數名字,這個可以自定義
括號裏面傳遞的是函數的參數,改參數在函數中都可以使用
return 是錶帶當我們調用函數的時候返回的結果。
2.函數的各種類型參數
1.實例1:
def fun1(a,b=0):
print a
print b
fun1(1)
結果爲:
1
0
如果把fun1(1)改爲fun1(1,2),結果爲:
1
2
fun1(a,b=0)其實是給b 設置了一個默認參數,如果沒有給b設置參數,b就是0,設置了參數,優先使用設置的實參。
2.參數爲tuple, man(m,*args)
def fun2(a,b,*c):
print a
print b
print 'leng c is %d' % len(c)
print c
fun2(1,2,3,4,5,6)
結果爲:
1
2
leng c is 4
(3, 4, 5, 6)
也可以這樣寫
def fun2(a,b,*c):
print a
print b
print 'leng c is %d' % len(c)
print c
#fun2(1,2,3,4,5,6)
tub = ('hello','world')
fun2(1,2,*tub) #用星號
3.參數爲字典,man(m,**args) 兩個星號
def fun3(a,**b):
print(a)
print(b)
for x in b:
print x + ':' + str(b[x])
fun3(100,x='hello',y='你好')
結果爲:
100
{'y': '\xe4\xbd\xa0\xe5\xa5\xbd', 'x': 'hello'}
y:你好
x:hello
也可以用**去寫
n3(a,**b):
print(a)
print(b)
for x in b:
print x + ':' + str(b[x])
fun3(100,x='hello',y='你好')
args = {'1':'abc','b':'hello'}
fun3(100,**args)
結果爲:
100
{'y': '\xe4\xbd\xa0\xe5\xa5\xbd', 'x': 'hello'}
y:你好
x:hello
100
{'1': 'abc', 'b': 'hello'}
1:abc
b:hello