6.函数与lambda表达式

1.定义函数:关键词def 引入一个函数定义,其后必须跟函数名称和带括号的形式参数列表,而函数的语句需要从下一行开始,并且必须缩进。
注意:(1)函数名称的值具有解释器,可以将其之别作为用户定义函数的类型,这个值一般可以分配给另一个名称,该名称就可以作为一个函数使用,即重命名机制.

def fib(n):
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a + b
    print()  # 0 1 1 2 3 5 
fib(6)  
f = fib
f(100)  # 0 1 1 2 3 5 8 13 21 34 55 89 

(2)fib 在这里作为函数名,当输入fib 时,即使没有 return 语句的函数也会返回一个值,None(内置名称),一般不显示,可以使用print().

f(0)
print(f(0))  # None

2.参数默认值:对一个或多个参数指定一个默认值。这样创建的函数,可以用比定义时允许的更少的参数调用.

def ask_ok(prompt, retries=4, reminder='Please try again!'):
    while True:
        ok = input(prompt)
        if ok in ('y', 'ye', 'yes'):
            print('www')
        if ok in ('n', 'no', 'nop', 'nope'):
            print('qqq')
        retries = retries - 1
        if retries < 0:
            raise ValueError('invalid user response')
        print(reminder)
ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')
OK to overwrite the file?y
www
Come on, only yes or no!

根据此题可以给出下面几种调用方式:
a.只给出必需的参数:

ask_ok('Do you really want to quit?')

b.给出一个可选的参数:

ask_ok('OK to overwrite the file?', 2)

c.给出所有的参数:

ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')

注意:默认值只会执行一次,函数会存储在后续调用中传递给它的参数。

def f(a, L=[]):
    L.append(a)
    return L
print(f(1))  # [1]
print(f(2))  # [1, 2]
print(f(3))  # [1, 2, 3]

改进:

def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L
print(f(1))  # [1]
print(f(2))  # [2]
print(f(3))  # [3]

3.关键字参数:下面例题中,有一个必须的参数和三个可选的参数。

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)   
-- This parrot wouldn't voom if you put 1000 volts through it.
-- Lovely plumage, the Norwegian Blue
-- It's a stiff !                                    

除了上述调用方法,只要保持必须的参数赋值即可,否则调用无效,同时注意关键字参数的顺序保证与调用函数时提供它们的顺序是相匹配的,如:

parrot(voltage=1000)                                  
parrot(voltage=1000000, action='VOOOOOM')             
parrot(action='VOOOOOM', voltage=1000000)             
parrot('a million', 'bereft of life', 'jump')         
parrot('a thousand', state='pushing up the daisies')

-- This parrot wouldn't voom if you put 1000 volts through it.
-- Lovely plumage, the Norwegian Blue
-- It's a stiff !
-- This parrot wouldn't VOOOOOM if you put 1000000 volts through it.
-- Lovely plumage, the Norwegian Blue
-- It's a stiff !
-- This parrot wouldn't VOOOOOM if you put 1000000 volts through it.
-- Lovely plumage, the Norwegian Blue
-- It's a stiff !
-- This parrot wouldn't jump if you put a million volts through it.
-- Lovely plumage, the Norwegian Blue
-- It's bereft of life !
-- This parrot wouldn't voom if you put a thousand volts through it.
-- Lovely plumage, the Norwegian Blue
-- It's pushing up the daisies !

4.Lambda 表达式:创建一个小的匿名函数,在语法上限于单个表达式,这个函数返回两个参数的和: lambda a, b: a+b 。

def ff(n):
    return lambda x: x + n
f = ff(5)
print(f(6))  # 11

传递一个小函数作为参数

pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
print(pairs)  # [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值