python基础课程系列(七)

8.3.返回值
函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。函数返回的值被称为 返回值 。在函数中,可使用 return 语句将值返回到调用函数的代码行。
8.3.1.返回简单值

def get_formatted_name(first_name, last_name):
    full_name = first_name + ' ' + last_name
    return full_name.title()

-------------------------------------------------------
>>> musician = get_formatted_name('jimi', 'hendrix')
>>> print(musician)
Jimi Hendrix

8.3.2.让实参变成可选的
有时候,需要让实参变成可选的,这样使用函数的人就只需在必要时才提供额外的信息。可使用默认值来让实参变成可选的

def get_formatted_name(first_name, middle_name, last_name):
    full_name = first_name + ' ' + middle_name + ' ' + last_name
    return full_name.title()
-------------------------------------------------------
>>> musician = get_formatted_name('john', 'lee', 'hooker')
>>> print(musician)
John Lee Hooker

然而,并非所有的人都有中间名,但如果你调用这个函数时只提供了名和姓,它将不能正确地运行。为让中间名变成可选的,可给实参 middle_name 指定一个默认值 —— 空字符串,并在用户没有提供中间名时不使用这个实参。

ef get_formatted_name(first_name, last_name,  middle_name=''):
    if middle_name:
        full_name = first_name + ' ' + middle_name + ' ' + last_name
    else:
        full_name = first_name + ' ' + last_name

    return full_name.title()
-------------------------------------------------------
>>> musician = get_formatted_name('jimi', 'hendrix')
>>> print(musician)
Jimi Hendrix
>>> musician = get_formatted_name('john', 'hooker', 'lee')
>>> print(musician)
John Lee Hooker

8.3.3.返回字典
函数可返回任何类型的值,包括列表和字典等较复杂的数据结构。

def build_person(first_name, last_name):
    person = {'first':first_name, 'last':last_name}

    return person
------------------------------------------------------
>>> musician = build_person('jimi', 'hendrix')
>>> print(musician)
{'first': 'jimi', 'last': 'hendrix'}

8.3.4.结合使用函数和 while  循环

def get_formatted_name(fitst_name, last_name):
    full_name = fitst_name + ' ' + last_name
    return full_name

while True:
    print('\nPlease tell me your name:')
    print('(enter \'q\' at an time to quit)')

    f_name = input('First name:')
    if f_name == 'q':
        break
    
    l_name = input('Last name:')
    if l_name == 'q':
        break
    
    formatted_name = get_formatted_name(f_name, l_name)
    print('\nHello, ' + formatted_name +'!')

------------------------------------------------------
Please tell me your name:
(enter 'q' at an time to quit)
First name:eric
Last name:matthes

Hello, eric matthes!

Please tell me your name:
(enter 'q' at an time to quit)
First name:q

8.4.传递列表
向函数传递列表很有用,这种列表包含的可能是名字、数字或更复杂的对象(如字典)。将列表传递给函数后,函数就能直接访问其内容。
------------------------------------------------------
def greet_users(names):
    for name in names:
        msg = 'Hello, ' + name.title() + '!'
        print(msg)

usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
------------------------------------------------------
Hello, Hannah!
Hello, Ty!
Hello, Margot!

8.4.1.在函数中修改列表
这个程序首先创建一个需要打印的设计列表,还创建一个名为 completed_models 的空列表,每个设计打印都将移到这个列表中。只要列表 unprinted_designs 中还有设计, while 循环就模拟打印设计的过程:从该列表末尾删除一个设计,将其存储到变量 current_design 中,并显示一条消息,指出正在打印当前的设计,再将该设计加入到列表 completed_models 中。循环结束后,显示已打印的所有设计:
-------------------------------------------------------
#首先创建一个列表,其中包含一些要打印的设计
unprinted_designs = ['iphone cases', 'robot pendant', 'dodecahedron']
completed_models = []

#模拟打印每个设计,直到没有未打印的设计为止
#打印每个设计后,都将其移到列表completed_models中

while unprinted_designs:
    current_design = unprinted_designs.pop()

    print('Printing model: ' + current_design)
    completed_models.append(current_design)

#显示打印好的所有模型
print('\nThe following models have been printed:')
for completed_model in completed_models:
    print(completed_model)
-------------------------------------------------------
Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone cases

The following models have been printed:
dodecahedron
robot pendant
iphone cases

为重新组织这些代码,我们可编写两个函数,每个都做一件具体的工作。大部分代码都与原来相同,只是效率更高。第一个函数将负责处理打印设计的工作,而第二个将概述打印了哪些设计:
------------------------------------------------------
def print_models(unprint_designs, completed_models):
    while unprinted_designs:
        current_design = unprinted_designs.pop()

        print('Printing model: ' + current_design)
        completed_models.append(current_design)

def show_completed_models(completed_models):
    print('\nThe following models have been printed:')
    for completed_model in completed_models:
        print(completed_model)
-------------------------------------------------------
>>> unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
>>> completed_models = []
>>> print_models(unprinted_designs, completed_models)
Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone case

>>> show_completed_models(completed_models)

The following models have been printed:
dodecahedron
robot pendant
iphone case

8.5.传递任意数量的实参
有时候,你预先不知道函数需要接受多少个实参,好在 Python 允许函数从调用语句中收集任意数量的实参。
例如,来看一个制作比萨的函数,它需要接受很多配料,但你无法预先确定顾客要多少种配料。下面的函数只有一个形参 *toppings ,但不管调用语句提供了多少实参,这个
形参都将它们统统收入囊中:
-------------------------------------------------------
def make_pizza(*toppings):
    print('\nMaking a pizza with the following toppings:')
    for topping in toppings:
        print('- ' + topping)
-------------------------------------------------------
>>> make_pizza('pepperoni')

Making a pizza with the following toppings:
- pepperoni
>>> make_pizza('mushrooms', 'green peppers', 'extra cheese')

Making a pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese

8.5.1.结合使用位置实参和任意数量实参
如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。 Python 先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中。
------------------------------------------------------
def make_pizza(size, *toppings):
    print('\nMaking a ' + str(size) +
          '-inch pizza with the following toppings:')
    for topping in toppings:
        print('- ' + topping)
-------------------------------------------------------
>>> make_pizza(16, 'pepperoni')

Making a 16-inch pizza with the following toppings:
- pepperoni
>>> make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese

8.5.2.使用任意数量的关键字实参
有时候,需要接受任意数量的实参,但预先不知道传递给函数的会是什么样的信息。在这种情况下,可将函数编写成能够接受任意数量的键 — 值对 —— 调用语句提供了多少就接
受多少。
-------------------------------------------------------
def build_profile(first, last, **user_info):
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last

    for key, value in user_info.items():
        profile[key] = value

    return profile
-------------------------------------------------------
>>> user_profile = build_profile('albert', 'einstein', location='princeton', field='physics')
>>> print(user_profile)
{'last_name': 'einstein', 'field': 'physics', 'first_name': 'albert', 'location': 'princeton'}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值