怎樣才能寫好一個Python函數?
在Python中定義函數。
1. 比如用Python寫一個斐波那契數列函數:
>>> def fib(n): # write Fibonacci series up to n
... """Print a Fibonacci series up to n."""
... a, b = 0, 1
... while a < n:
... print(a, end=' ')
... a, b = b, a+b
... print()
...
函數調用:
>>> # Now call the function we just defined:
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
在Python函數中,def關鍵字聲明一個函數定義,函數名稱緊跟其后,函數名稱后面是包含參數列表的小括號,最后是冒號結尾。
然后Python函數的函數體從下一行開始,必須注意要有字符縮進。
Python的函數調用,比如:
>>> fib(0)
>>> print(fib(0))
None
2. fib(n)是沒有返回值的函數,下面寫一個有返回值的Python函數,返回[]list列表:
>>> def fib2(n): # return Fibonacci series up to n
... """Return a list containing the Fibonacci series up to n."""
... result = []
... a, b = 0, 1
... while a < n:
... result.append(a) # see below
... a, b = b, a+b
... return result
...
函數調用:
>>> f100 = fib2(100) # call it
>>> f100 # write the result
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
函數fib2(n)實例中展示了新的Python feature,其中return用于聲明當前函數返回一個值,result.append(a)調用了list對象result的append函數,append是由對象的類型決定的函數,實際上相當于result = result + [a],但是append的效率更高。
3. 在Python函數定義中定義多個參數列表,以及為參數賦上默認值:
def ask_ok(prompt, retries=4, reminder='Please try again!'):
while True:
ok = input(prompt)
if ok in ('y', 'ye', 'yes'):
return True
if ok in ('n', 'no', 'nop', 'nope'):
return False
retries = retries - 1
if retries < 0:
raise ValueError('invalid user response')
print(reminder)
這里又個非常重要的警告,需要在實際項目中多加注意!!默認值通常只計算一次,但是如果默認值是可變的,比如list,就會有如下情況:
def f(a, L=[]):
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))
輸出結果為:
[1]
[1, 2]
[1, 2, 3]
可以改為:
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
4. 函數里的關鍵字參數
形式是kwarg=value
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print("-- This parrot wouldn't", action, end=' ')
print("if you put", voltage, "volts through it.")
print("-- Lovely plumage, the", type)
print("-- It's", state, "!")
def cheeseshop(kind, *arguments, **keywords):
print("-- Do you have any", kind, "?")
print("-- I'm sorry, we're all out of", kind)
for arg in arguments:
print(arg)
print("-" * 40)
for kw in keywords:
print(kw, ":", keywords[kw])
5. 特殊參數
def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
----------- ---------- ----------
Positional or keyword
- Keyword only
-- Positional only
6. 注意函數的代碼風格和命名規范
比如使用4個空格鍵為不是tab縮進等。