第八章
8.1
练习8-1:消息
编写一个名为display_message()的函数,它打印一个句子,指出你在本章学的是什么。调用这个函数,确认显示的消息正确无误。
def display_message():
"""打印本章学到的内容,如谢帝谢帝我要迪士尼"""
print("In this chapter, I learned about functions in Python.")
# 调用函数
display_message()
练习8-2:喜欢的图书
编写一个名为favorite_book()的函数,其中包含一个名为title的形参。这个函数打印一条消息,下面是一个例子。
def favorite_book(title):
"""打印喜欢的图书"""
print(f"One of my favorite books is {title}.")
# 调用函数
favorite_book("Alice in Wonderland")
8.2
练习8-3:T恤 编写一个名为make_shirt()的函数,它接受一个尺码和要印到T恤上的字样。该函数应打印一个句子,概要地说明T恤的尺码和字样。使用位置实参和关键字实参分别调用该函数。
def make_shirt(size, message):
print(f"A {size} shirt will be printed with the message: {message}")
# 使用位置实参调用函数
make_shirt('medium', 'Hello, World!')
# 使用关键字实参调用函数
make_shirt(message='I love Python', size='large')
练习8-4:大号T恤 修改函数make_shirt(),使其在默认情况下制作一件印有“I love Python”字样的大号T恤。调用这个函数来制作:一件印有默认字样的大号T恤,一件印有默认字样的中号T恤,以及一件印有其他字样的T恤(尺码无关紧要)。
def make_shirt(size='large', message='I love Python'):
print(f"A {size} shirt will be printed with the message: {message}")
# 默认字样的大号T恤
make_shirt()
# 默认字样的中号T恤
make_shirt(size='medium')
# 其他字样的T恤
make_shirt(message='Hello, World!')
练习8-5:城市 编写一个名为describe_city()的函数,它接受一座城市的名字以及该城市所属的国家。该函数应打印一个简单的句子,说明城市所属的国家。给用于存储国家的形参指定默认值。为三座不同的城市调用这个函数,且其中至少有一座城市不属于默认国家。
def describe_city(city, country='China'):
print(f"{city.title()} is in {country}.")
# 调用函数,指定城市所属的国家
describe_city('beijing')
describe_city('paris', 'France')
describe_city('tokyo', 'Japan')
8.3
练习8-6:城市名 编写一个名为city_country()的函数,它接受城市的名称及其所属的国家。该函数应返回一个格式类似于"Santiago, Chile"的字符串。
def city_country(city, country):
return f"{city.title()}, {country.title()}"
# 调用函数并打印返回值
print(city_country('santiago', 'chile'))
print(city_country('beijing', 'china'))
print(city_country('tokyo', 'japan'))
练习8-7:专辑 编写一个名为make_album()的函数,它创建一个描述音乐专辑的字典。该函数应接受歌手的名字和专辑名,并返回一个包含这两项信息的字典。使用这个函数创建三个表示不同专辑的字典,并打印每个返回的值,以核实字典正确地存储了专辑的信息。给函数make_album() 添加一个默认值为None的可选形参,以便存储专辑包含的歌曲数。如果调用这个函数时指定了歌曲数,就将该值添加到表示专辑的字典中。调用这个函数,并至少在一次调用中指定专辑包含的歌曲数。
def make_album(artist, album, tracks=None):
album_info = {'artist': artist, 'album': album}
if tracks:
album_info['tracks'] = tracks
return album_info
# 创建专辑字典并打印返回值
print(make_album('Taylor Swift', '1989'))
print(make_album('Ed Sheeran', '÷', 16))
print(make_album('Beyoncé', 'Lemonade', 12))
练习8-8:用户的专辑 在为完成练习8-7编写的程序中,编写一个while循环,让用户输入专辑的歌手和名称。获取这些信息后,使用它们来调用函数make_album() 并将创建的字典打印出来。在这个while循环中,务必提供退出途径。
def make_album(artist, album, tracks=None):
album_info = {'artist': artist, 'album': album}
if tracks:
album_info['tracks'] = tracks
return album_info
while True:
artist = input("Enter the artist's name (enter 'quit' to exit): ")
if artist == 'quit':
break
album = input("Enter the album's name (enter 'quit' to exit): ")
if album == 'quit':
break
print(make_album(artist, album))
8.4
练习8-9:消息 创建一个列表,其中包含一系列简短的文本消息。将该列表 传递给一个名为show_messages() 的函数,这个函数会打印列表中的每条文 本消息。
def show_messages(messages):
for message in messages:
print(message)
messages = ["Hello!", "How are you?", "Good morning!"]
show_messages(messages)
练习8-10:发送消息 在你为完成练习8-9而编写的程序中,编写一个名为 send_messages() 的函数,将每条消息都打印出来并移到一个名为 sent_messages 的列表中。调用函数send_messages() ,再将两个列表都 打印出来,确认正确地移动了消息。
def send_messages(messages, sent_messages):
while messages:
current_message = messages.pop(0)
print(f"Sending message: {current_message}")
sent_messages.append(current_message)
messages = ["Hello!", "How are you?", "Good morning!"]
sent_messages = []
send_messages(messages, sent_messages)
print("\nOriginal messages:")
print(messages)
print("\nSent messages:")
print(sent_messages)
练习8-11:消息归档 修改你为完成练习8-10而编写的程序,在调用函数 send_messages() 时,向它传递消息列表的副本。调用函数 send_messages() 后,将两个列表都打印出来,确认保留了原始列表中的消 息。
def send_messages(messages, sent_messages):
while messages:
current_message = messages.pop(0)
print(f"Sending message: {current_message}")
sent_messages.append(current_message)
messages = ["Hello!", "How are you?", "Good morning!"]
sent_messages = []
send_messages(messages[:], sent_messages)
print("\nOriginal messages:")
print(messages)
print("\nSent messages:")
print(sent_messages)
8.5
练习8-12:三明治 编写一个函数,它接受顾客要在三明治中添加的一系列食 材。这个函数只有一个形参(它收集函数调用中提供的所有食材),并打印一 条消息,对顾客点的三明治进行概述。调用这个函数三次,每次都提供不同数 量的实参。
def make_sandwich(*ingredients):
print("\nMaking a sandwich with the following ingredients:")
for ingredient in ingredients:
print("- " + ingredient)
make_sandwich('ham', 'cheese', 'lettuce')
make_sandwich('turkey', 'swiss cheese', 'tomato', 'mayonnaise')
make_sandwich('roast beef', 'cheddar cheese', 'onion', 'mustard', 'pickles')
练习8-13:用户简介 复制前面的程序user_profile.py,在其中调用 build_profile() 来创建有关你的简介。调用这个函数时,指定你的名和 姓,以及三个描述你的键值对。
def build_profile(first_name, last_name, **user_info):
profile = {}
profile['first_name'] = first_name
profile['last_name'] = last_name
for key, value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('John', 'Doe', location='New York', occupation='Engineer', age=30)
print(user_profile)
练习8-14:汽车 编写一个函数,将一辆汽车的信息存储在字典中。这个函数 总是接受制造商和型号,还接受任意数量的关键字实参。这样调用该函数:提 供必不可少的信息,以及两个名称值对,如颜色和选装配件。这个函数必须能 够像下面这样进行调用:
car = make_car('subaru', 'outback', color='blue', tow_package=True)
打印返回的字典,确认正确地处理了所有的信息。
def make_car(manufacturer, model, **car_info):
car = {'manufacturer': manufacturer, 'model': model}
for key, value in car_info.items():
car[key] = value
return car
car = make_car('subaru', 'outback', color='blue', tow_package=True)
print(car)
8.6
练习8-15:打印模型 将示例printing_models.py中的函数放在一个名为 printing_functions.py的文件中。在printing_models.py的开头编写一条 import 语句,并修改该文件以使用导入的函数。
printing_functions.py
def print_models(models):
"""Simulate printing each design in the list."""
print("Printing models:")
for model in models:
print("- " + model)
def show_completed_models(completed_models):
"""Show all the models that were printed."""
print("\nThe following models have been printed:")
for model in completed_models:
print("- " + model)
printing_models.py
import printing_functions
unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = []
printing_functions.print_models(unprinted_designs)
printing_functions.show_completed_models(completed_models)
练习8-16:导入 选择一个你编写的且只包含一个函数的程序,将该函数放在 另一个文件中。在主程序文件中,使用下述各种方法导入这个函数,再调用它: import module_name from module_name import function_name from module_name import function_name as fn import module_name as mn from module_name import *
function.py
def greet_user(username):
"""Display a simple greeting."""
print("Hello, " + username.title() + "!")
main.py
# 方法1:import module_name
import function
function.greet_user('Alice')
# 方法2:from module_name import function_name
from function import greet_user
greet_user('Bob')
# 方法3:from module_name import function_name as fn
from function import greet_user as greet
greet('Charlie')
# 方法4:import module_name as mn
import function as fn
fn.greet_user('David')
# 方法5:from module_name import *
from function import *
greet_user('Emily')
练习8-17:函数编写指南 选择你在本章中编写的三个程序,确保它们遵循了 本节介绍的函数编写指南。
略