Python基础之函数

  1. 简单的函数定义如下
# 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()
  1. Default Argument Values
    default argument又称为optional argument,可以不传递。其他参数称为required argument,必须传递。
def ask_ok(prompt, retries=4, reminder='Please try again!'):
#可以通过以下方式调用该函数 
ask_ok('hello')
ask_ok('hello', 2)
ask_ok('hello', 2, 'world!')
  1. Keyword Arguments(kwarg=value)
    除了通过上述方式传参,还可以指定参数名称传参。
  • key argument必须在positional argument之后调用。
  • key argument的顺序不重要
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
#可以通过以下方式调用该函数
parrot(1000)   #positional argument
parrot(voltage=1000000, action='VOOOOOM')             # 2 keyword arguments

#不合法调用,key argument必须在positional argument之后调用
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
  1. 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])
  1. Unpacking Argument Lists
可以通过`*``**`解包list或dictionary传给参数
def parrot(voltage, state='a stiff', action='voom')

>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
  1. 查看函数文档
print(my_function.__doc__)

reference

https://docs.python.org/3/tutorial/controlflow.html#defining-functions

你可能感兴趣的:(Python基础之函数)