函数

定义函数

>>> 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

函数式可以当变量传递的

>>> fib

<function fib at 10042ed0>

>>> f = fib

>>> f(100)

0 1 1 2 3 5 8 13 21 34 55 89

带返回值的函数

>>> 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]

参数默认值

def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):

    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 IOError('refusenik user')

        print(complaint)

默认值可以是变量,这个挺狠。。。

i = 5



def f(arg=i):

    print(arg)



i = 6

f()

命名参数

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, "!")



parrot(1000)                                          # 1 positional argument

parrot(voltage=1000)                                  # 1 keyword argument

parrot(voltage=1000000, action='VOOOOOM')             # 2 keyword arguments

parrot(action='VOOOOOM', voltage=1000000)             # 2 keyword arguments

parrot('a million', 'bereft of life', 'jump')         # 3 positional arguments

parrot('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword

下面是不合法的命名参数

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

可变参数个数

def write_multiple_items(file, separator, *args):

    file.write(separator.join(args))



>>> def concat(*args, sep="/"):

...    return sep.join(args)

...

>>> concat("earth", "mars", "venus")

'earth/mars/venus'

>>> concat("earth", "mars", "venus", sep=".")

'earth.mars.venus'

*和**用开解包参数

>>> list(range(3, 6))            # normal call with separate arguments

[3, 4, 5]

>>> args = [3, 6]

>>> list(range(*args))            # call with arguments unpacked from a list

[3, 4, 5]
>>> def parrot(voltage, state='a stiff', action='voom'):

...     print("-- This parrot wouldn't", action, end=' ')

...     print("if you put", voltage, "volts through it.", end=' ')

...     print("E's", state, "!")

...

>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}

>>> parrot(**d)

-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

 Document string 用来描述函数

>>> def my_function():

...     """Do nothing, but document it.

...

...     No, really, it doesn't do anything.

...     """

...     pass

...

>>> print(my_function.__doc__)

Do nothing, but document it.



    No, really, it doesn't do anything.

 函数注解,暂时没弄明白

>>> def f(ham: 42, eggs: int = 'spam') -> "Nothing to see here":

...     print("Annotations:", f.__annotations__)

...     print("Arguments:", ham, eggs)

...

>>> f('wonderful')

Annotations: {'eggs': <class 'int'>, 'return': 'Nothing to see here', 'ham': 42}

Arguments: wonderful spam

 

 

你可能感兴趣的:(函数)