1.def (define的前三個字母)是一個關鍵字,用來聲明函數。
2.def 聲明函數的格式為:
def 函數名(參數1,參數2,...,參數n):
函數體
例如:
def fib(n):
print 'n =', n
if n > 1:
return n * fib(n - 1) else:
print 'end of the line' return 1
3.函數返回值類型不固定,聲明函數時不需要指定其返回值的數據類型。
4.函數甚至可以沒有返回值,如果沒有返回值,系統回默認返回空值 None。
5.可選參數:可以指定參數的默認值,如果調用時沒有指定參數,將取默認值。
例如:
def approximate_size(size, a_kilobyte_is_1024_bytes=True):
print(approximate_size(1000000000000,False)) ①
print(approximate_size(1000000000000)) ②
6.命名參數:通過使用命名參數還可以按照任何順序指定參數。只要你有一個命名參數,它右邊的所有參數也都需要是命名參數。
例如:
>>>from humansize import approximate_size>>>approximate_size(4000, a_kilobyte_is_1024_bytes=False) ①
'4.0 KB'>>>approximate_size(size=4000, a_kilobyte_is_1024_bytes=False) ②
'4.0 KB'>>>approximate_size(a_kilobyte_is_1024_bytes=False, size=4000) ③
'4.0 KB'>>>approximate_size(a_kilobyte_is_1024_bytes=False,4000) ④
File "<stdin>", line 1 SyntaxError: non-keyword arg after keyword arg>>>approximate_size(size=4000,False) ⑤
File "<stdin>", line 1 SyntaxError: non-keyword arg after keyword arg