greeter.py
def greet_user(username):
"""显示简单的问候语."""
print(f"Hello, {username.title()}")
greet_user('jesse')
display_message.py
# 练习 8-1 消息
# 编写一个名为 display_message() 的函数,它打印一个句子,指出你在本章学的是什么。
# 调用这个函数,确认显示的消息正确无误。
def display_message():
"""显示一条消息,指出你在本章学的是什么."""
msg = "I'm learning to store code in functions."
print(msg)
display_message()
favorite_book.py
# 练习 8-2 喜欢的图书
# 编写一个名为 favorite_book() 的函数,其中包含一个名为 title 的形参。
# 这个函数打印一条消息,如 One of my favorite books is Alice in Wonderland。
# 调用这个函数,并将一本图书的名称作为实参传递给它。
def favorite_book(title):
"""显示一条消息,指出喜欢的一本图书。"""
print(f"{title} is one of my favorite books.")
favorite_book('Alice in Wonderland')
pets.py
def describe_pet(animal_type, pet_name):
"""显示宠物的信息"""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
# 位置实参
describe_pet('hamster', 'harry')
# 再次传递参数
describe_pet('dog', 'willie')
# 位置实参
describe_pet(animal_type='hamster', pet_name='harry')
describe_pet(pet_name='harry', animal_type='hamster')
pets1.py
# 给其中形参设置默认值
def describe_pet(pet_name, animal_type='dog'):
"""显示宠物的信息"""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(pet_name='willie')
describe_pet('willie')
# 等效的函数调用
describe_pet('harry', 'hamster')
describe_pet(pet_name='harry', animal_type='hamster')
describe_pet(animal_type='hamster',pet_name='harry')
make_shirt.py
# 练习 8-3 T 恤
# 编写一个名为 make_shirt() 的函数,它接受尺码以及要印到 T 恤上的字样。
# 这个函数应打印一个句子,概要地说明 T 恤衫的尺码和字样。
# 使用位置实参调用这个函数来制作一件 T 恤,再使用关键字实参来调用这个函数。
def make_shirt(size, message):
"""概述要制作的 T 恤什么样。"""
print(f"\nI'm going to make a {size} T-shirt.")
print(f'It will say, "{message}"')
make_shirt('large', 'I love Python!')
make_shirt1.py
# 练习 8-4 大号 T 恤
# 修改函数 make_shirt() ,使其在默认情况下制作一件印有
# “I love Python” 字样的大号 T 恤。
# 调用这个函数来制作如下 T 恤:一件印有默认字样的大号 T 恤、
# 一件印有默认字样的中号 T 恤、一件印有其他字样的 T 恤(尺码无关紧要)。
def make_shirt(size='large', message='I love Python!'):
"""概述要制作的 T 恤什么样。"""
print(f"\nI'm going to make a {size} T-shirt.")
print(f'It will say, "{message}"')
make_shirt()
make_shirt(size='medium')
make_shirt(message='I love Py...')
describe_city.py
# 练习 8-5 城市
# 编写一个名为 describe_city() 的函数,它接受一座城市的名称和所属的国家。
# 这个函数应打印一个简单的句子,如 Reykjavik is in Iceland。
# 给用于存储国家的形参指定默认值。为三座不同的城市调用这个函数,
# 且其中至少有一座城市不属于默认国家。
def describe_city(city, country='chile'):
"""描述城市."""
msg = f"{city.title()} is in {country}."
print(msg)
describe_city('santiago')
describe_city('reykjavik', 'iceland')
describe_city('punta arenas')
formatted_name.py
# 返回值
def get_formatted_name(first_name, middle_name,last_name):
"""返回整洁的值."""
full_name = f"{first_name} {middle_name} {last_name}"
return full_name.title()
musician = get_formatted_name('john', 'lee', 'hooker')
print(musician)
formatted_name1.py
# 让实参变成可选的
def get_formatted_name(first_name, last_name, middle_name=''):
"""返回整洁的姓名."""
if middle_name:
full_name = f"{first_name} {middle_name} {last_name}"
else:
full_name = f"{first_name} {last_name}"
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
musician = get_formatted_name('john', 'hooker', 'lee')
print(musician)
person.py
# 返回字典
def build_person(first_name, last_name):
"""返回一个字典,其中包含有关一个人的信息."""
person = {'first': first_name, 'last': last_name}
return person
musician = build_person('jimi', 'hendrix')
print(musician)
person1.py
def build_person(first_name, last_name, age=None):
"""返回一个字典,其中包含有关一个人的信息."""
person = {'first': first_name, 'last': last_name}
if age:
person['age'] = age
return person
musician = build_person('jimi', 'hendrix', age=27)
print(musician)
greeter1.py
def get_formatted_name(first_name, last_name):
"""返回整洁的姓名."""
full_name = f"{first_name} {last_name}"
return full_name.title()
# 这是一个无限循环
while True:
print("\nPlease tell me your name:")
print("(Enter 'q' at any 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(f"\nHello, {formatted_name}!")
city_country.py
# 练习 8-6 城市名
# 编写一个名为 city_country() 的函数,它接受城市的名称和所属的国家。
# 这个函数应返回一个格式类似于下面的字符串:"Santiago, Chile"
# 至少使用三个城市-国家对调用这个函数,并打印返回的值。
def city_country(city, country):
"""返回一个格式类似于'Santiago, Chile'的字符串"""
return f"{city.title()}, {country.title()}"
city = city_country('santiago', 'chile')
print(city)
city = city_country('ushuaia', 'argentina')
print(city)
city = city_country('longyearbyen', 'svalbard')
print(city)
make_album.py
# 练习 8-7 专辑
# 编写一个名为 make_album() 的函数,它创建一个描述音乐专辑的字典。
# 这个函数应接受歌手的名字和专辑名,并返回一个包含这两项信息的字典。
# 使用这个函数创建三个表示不同专辑的字典,并打印每个返回的值,
# 以核实字典正确地存储了专辑的信息。给函数 make_album() 添加一个可选形参,
# 以便能够存储专辑包含的歌曲数。
# 如果调用这个函数时指定了歌曲数,就将这个值添加到表示专辑的字典中。
# 调用这个函数,并至少在一次调用中指定专辑包含的歌曲数。
def make_album(artist, title, tracks=None):
"""创建一个包含专辑信息的字典."""
album_dict = {
'artist': artist.title(),
'title': title.title(),
}
if tracks:
album_dict['tracks'] = tracks
return album_dict
album = make_album('metallica', 'ride the lightning')
print(album)
album = make_album('beethoven', 'ninth symphony')
print(album)
album = make_album('willie nelson', 'red-headed stranger')
print(album)
album = make_album('iron maiden', 'piece of mind', tracks=8)
print(album)
make_album1.py
# 练习 8-8 用户的专辑
# 在为完成练习 8-7 编写的程序中,编写一个 while 循环,
# 让用户输入一个专辑的歌手和名称。
# 获取这些信息后,使用它们来调用函数 make_album() 并将创建的字典打印出来。
# 在这个 while 循环中,务必提供退出途径。
def make_album(artist, title, tracks=None):
"""创建一个包含专辑信息的字典."""
album_dict = {
'artist': artist.title(),
'title': title.title(),
}
if tracks:
album_dict['tracks'] = tracks
return album_dict
# 生成提示语.
title_prompt = "\nWhat album are you thinking of? "
artist_prompt = "Who the artist? "
# 让用户知道如何退出.
print("Enter 'q' at any time to quit." )
while True:
title = input(title_prompt)
if title == 'q':
break
artist = input(artist_prompt)
if artist == 'q':
break
album = make_album(artist, title)
print(album)
print("\nThanks for responding!")
greeter_users.py
# 传递列表
def greet_users(names):
"""向列表中的每位用户发出简单的问候."""
for name in names:
msg = f"Hello, {name.title()}!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
printing_models.py
# 在函数中修改列表
# 首先创建一个列表,其中包含一些要打印的设计.
unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = []
# 模拟打印每个设计,直到没有未打印的设计为止.
# 打印每个设计后,都将其移到列表completed_models中.
while unprinted_designs:
current_design = unprinted_designs.pop()
print(f"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)
message.py
# 练习 8-9 消息
# 创建一个列表,其中包含一系列简短的文本消息;
# 将这个列表传递给一个名为show_messages() 的函数,它打印列表中的每条文本消息。
def show_messages(messages):
"""打印列表中的所有消息"""
for message in messages:
print(message)
message = ["hello!", "hey!", "yaaa!"]
show_messages(message)
send_message.py
# 练习 8-10 发送消息
# 在你为完成练习 8-9 而编写的程序中,编写一个名为 send_messages() 的函数,
# 将每条消息都打印出来并移到一个名为 sent_messages 的列表中。
# 调用函数 send_messages() ,再将两个列表都打印出来,确认正确地移动了消息。
def show_messages(messages):
"""打印列表中的所有消息."""
for message in messages:
print(message)
def send_messages(messages,sent_messages):
"""打印每条消息,再将其移到列表sent_messages中."""
print("\nSending all messages:")
while messages:
current_message = messages.pop()
print(current_message)
sent_messages.append(current_message)
messages = ["hello!", "hey!", "yaaa!"]
show_messages(messages)
sent_messages = []
send_messages(messages,sent_messages)
print("\nFinal lists:")
print(messages)
print(sent_messages)
send_message1.py
# 练习 8-11 消息归档
# 修改你为完成练习 8-10 而编写的程序,
# 在调用函数 send_messages() 时,向它传递消息列表的副本。
# 调用函数 send_messages() 后,将两个列表都打印出来,确认保留了原始列表中的消息。
def show_messages(messages):
"""打印列表中的所有消息."""
for message in messages:
print(message)
def send_messages(messages,sent_messages):
"""打印每条消息,再将其移到列表sent_messages中."""
print("\nSending all messages:")
while messages:
current_message = messages.pop()
print(current_message)
sent_messages.append(current_message)
messages = ["hello!", "hey!", "yaaa!"]
show_messages(messages)
sent_messages = []
send_messages(messages[:],sent_messages)
print("\nFinal lists:")
print(messages)
print(sent_messages)
pizza.py
# 传递任意数量的实参
def make_pizza(*toppings):
"""概述要制作的比萨."""
print("\nMaking a pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
pizza1.py
# 结合使用位置实参和任意数量实参
def make_pizza(size, *toppings):
"""概述要制作的比萨."""
print(f"\nMaking a {size}-inch pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
user_profile.py
# 使用任意数量的关键字实参
def build_profile(first, last, **user_info):
"""创建一个字典,其中包含我们知道的有关用户的一切."""
user_info['first_name'] = first
user_info['last_name'] = last
return user_info
user_profile = build_profile('albert', 'einstein',
location='princeton',
field='physics',
)
print(user_profile)
make_sandwich.py
# 练习 8-12 三明治
# 编写一个函数,它接受顾客要在三明治中添加的一系列食材。这个函数只有一个形参
# (它收集函数调用中提供的所有食材),并打印一条消息,对顾客点的三明治进行概述。
# 调用这个函数三次,每次都提供不同数量的实参。
def make_sandwich(*items):
"""使用制定的食材制作三明治"""
print("\nI'll make you a great sandwich:")
for item in items:
print(f" ...adding {item} to your sandwich.")
print("Your sandwich is ready!")
make_sandwich('roast beef', 'cheddar cheese', 'lettuce', 'honey dijon')
make_sandwich('turkey', 'apple slices', 'honey mustard')
make_sandwich('peanut butter', 'strawberry jam')
user_profile1.py
# 练习 8-13: 用户简介
# 复制前面的程序user_profile.py,在其中调用build_profile()来创建有关你的简介.
# 调用这个函数时,指定你的名和姓,以及三个描述你的键值对.
def build_profile(first, last, **user_info):
"""创建一个字典,其中包含我们知道的有关用户的一切."""
user_info['first_name'] = first
user_info['last_name'] = last
return user_info
user_profile = build_profile('W', 'J',
age='4',
location='GX',
field='R.W',
)
print(user_profile)
car.py
# 练习 8-14 汽车
# 编写一个函数,将一辆汽车的信息存储在字典中。
# 这个函数总是接受制造商和型号,还接受任意数量的关键字实参。
# 这样调用这个函数:提供必不可少的信息,还有两个名称值对,如颜色和选装配件。
# 这个函数必须能够像下面这样进行调用:
# car = make_car('subaru', 'outback', color='blue', tow_package=True)
# 打印返回的字典,确认正确地处理了所有的信息。
def make_car(manufacturer, model, **options):
"""创建一个表示汽车的字典"""
car_dict= {
'manufacturer': manufacturer.title(),
'model': model.title(),
}
for option, value in options.items():
car_dict[option] = value
return car_dict
my_outback = make_car('subaru', 'outback', color='blue', tow_package=True)
print(my_outback)
my_old_accord = make_car('honda', 'accord', year=1991, color='white',
headlights='popup')
print(my_old_accord)
--------------------------------------------------------------------------------------------------------------------------
pizzas.py
"""模块文件"""
def make_pizza(size,*toppings):
"""概述要制作的比萨"""
print(f"\nMaking a {size}-inch pizza with the following toppings.")
for topping in toppings:
print(f"- {topping}")
--------------------------------------------------------------------------------------------------------------------------
# 导入pizzas.py整个模块
import pizzas
pizzas.make_pizza(16,'pepperoni')
pizzas.make_pizza(12,'mushrooms','green peppers','extra cheese')
--------------------------------------------------------------------------------------------------------------------------
# 导入特定的函数
from pizzas import make_pizza
make_pizza(16,'pepperoni')
make_pizza(12,'mushrooms','green peppers','extra cheese')
--------------------------------------------------------------------------------------------------------------------------
# 使用as给函数指定别名
from pizzas import make_pizza as mp
mp(16,'pepperoni')
mp(12,'mushrooms','green peppers','extra cheese')
--------------------------------------------------------------------------------------------------------------------------
# 使用as给模块指定别名
import pizzas as p
p.make_pizza(16,'pepperoni')
p.make_pizza(12,'mushrooms','green peppers','extra cheese')
--------------------------------------------------------------------------------------------------------------------------
# 使用星号(*)运算符导入模块之中的所有函数
from pizzas import *
make_pizza(16,'pepperoni')
make_pizza(12,'mushrooms','green peppers','extra cheese')
--------------------------------------------------------------------------------------------------------------------------
printing_functions.py
"""与打印 3D 模型相关的函数。"""
def print_models(unprinted_designs, completed_models):
"""
模拟打印每个设计,直到没有未打印的设计为止。
打印每个设计后,都将其移到列表 completed_models 中。
"""
while unprinted_designs:
current_design = unprinted_designs.pop()
# 模拟根据设计制作 3D 打印模型的过程。
print(f"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)
--------------------------------------------------------------------------------------------------------------------------
printing_models.py
# 练习 8-15 打印模型
# 将 printing_model.py中的函数放在另一个名为 printing_functions.py 的文件中。
# 在printing_models.py的开头编写一条 import 语句,并修改这个文件以使用导入的函数。
import printing_functions as pf
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
pf.print_models(unprinted_designs, completed_models)
pf.show_completed_models(completed_models)