- 簡單的函數(shù)定義如下
# def funcName(arg)
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()
- Default Argument Values
default argument又稱為optional argument,可以不傳遞沸呐。其他參數(shù)稱為required argument案怯,必須傳遞。
def ask_ok(prompt, retries=4, reminder='Please try again!'):
#可以通過以下方式調(diào)用該函數(shù)
ask_ok('hello')
ask_ok('hello', 2)
ask_ok('hello', 2, 'world!')
- Keyword Arguments(
kwarg=value
)
除了通過上述方式傳參,還可以指定參數(shù)名稱傳參馆里。
- key argument必須在positional argument之后調(diào)用轩勘。
- key argument的順序不重要
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
#可以通過以下方式調(diào)用該函數(shù)
parrot(1000) #positional argument
parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments
#不合法調(diào)用筒扒,key argument必須在positional argument之后調(diào)用
parrot() # required argument missing
parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument
parrot(110, voltage=220) # duplicate value for the same argument
parrot(actor='John Cleese') # unknown keyword argument
- Arbitrary Argument Lists
-
*
會被wrapped up成一個tuple -
**
會被wrapped up成一個dictionary
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])
- Unpacking Argument Lists
可以通過`*``**`解包list或dictionary傳給參數(shù)
def parrot(voltage, state='a stiff', action='voom')
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
- 查看函數(shù)文檔
print(my_function.__doc__)
reference
https://docs.python.org/3/tutorial/controlflow.html#defining-functions