《python编程从入门到实践》第2版 第八章课后练习

第八章

  • 练习8-1
  • 练习8-2
  • 练习8-3
  • 练习8-4
  • 练习8-5
  • 练习8-6
  • 练习8-7
  • 练习8-8
  • 练习8-9
  • 练习8-10
  • 练习8-11
  • 练习8-12
  • 练习8-13
  • 练习8-14
  • 练习8-15
  • 练习8-16
  • 练习8-17

练习8-1

消息 编写一个名为display_message() 的函数,它打印一个句子,指出你在本章学的是什么。调用这个函数,确认显示的消息正确无误。

def display_message():
    print("The content of this chapter is about functions.")
 
display_message()

输出:

The content of this chapter is about functions.

练习8-2

喜欢的图书 编写一个名为favorite_book() 的函数,其中包含一个名为 title 的形参。这个函数打印一条消息,下面是一个例子。
One of my favorite books is Alice in Wonderland.
调用这个函数,并将一本图书的名称作为实参传递给它。

def favorite_book(title):
    print(f"One of my favorite books is {title.title()}")
 
book = input('Which book is your favorite ? ')
favorite_book(book)

输出:

Which book is your favorite ? Alice in Wonderland
One of my favorite books is Alice In Wonderland

练习8-3

T恤 编写一个名为make_shirt() 的函数,它接受一个尺码以及要印到T恤上的字样。这个函数应打印一个句子,概要地说明T恤的尺码和字样。

使用位置实参调用该函数来制作一件T恤,再使用关键字实参来调用这个函数。

def make_shirt(size, word):
    print(f'This t-shirt is {size} and is printed with "{word}".')
 
word = input("It is printed your shirt: ")
size = input("Size: ")
make_shirt(size, word)

输出:

It is printed your shirt: Hello World!
Size: L
This t-shirt is L and is printed with "Hello World!".

练习8-4

大号T恤 修改函数make_shirt() ,使其在默认情况下制作一件印有“I love Python”字样的大号T恤。调用这个函数来制作:一件印有默认字样的大号T恤,一件印有默认字样的中号T恤,以及一件印有其他字样的T恤(尺码无关紧要)。

def make_shirt(size, word="I love Python"):
    print(f'This t-shirt is {size} and is printed with "{word}".')
 
make_shirt("XXL")
make_shirt("L")
make_shirt("S", "I love Java")

输出:

This t-shirt is XXL and is printed with "I love Python".
This t-shirt is L and is printed with "I love Python".
This t-shirt is S and is printed with "I love Java".

练习8-5

城市 编写一个名为describe_city() 的函数,它接受一座城市的名字以及该城市所属的国家。这个函数应打印一个简单的句子,下面是一个例子。

Reykjavik is in Iceland.

给用于存储国家的形参指定默认值。为三座不同的城市调用这个函数,且其中至少有一座城市不属于默认国家。

def describe_city(name, country='china'):
    print(f"{name.title()} is in {country.title()}.")
 
describe_city('beijing')
describe_city('tokyo', 'japan')
describe_city(name='Washington', country='america')

输出:

Beijing is in China.
Tokyo is in Japan.
Washington is in America.

练习8-6

城市名 编写一个名为city_country() 的函数,它接受城市的名称及其所属的国家。这个函数应返回一个格式类似于下面的字符串:

“Santiago, Chile”

至少使用三个城市国家对来调用这个函数,并打印它返回的值。

def city_country(name, country):
    country_name = f"{name} , {country}"
    return country_name.title()
 
name1 = city_country('beijing', 'china')
name2 = city_country('tokyo', 'japan')
name3 = city_country('Washington', 'america')
print(name1)
print(name2)
print(name3)

输出:

Beijing , China
Tokyo , Japan
Washington , America

练习8-7

专辑 编写一个名为make_album() 的函数,它创建一个描述音乐专辑的字典。这个函数应接受歌手的名字和专辑名,并返回一个包含这两项信息的字典。使用这个函数创建三个表示不同专辑的字典,并打印每个返回的值,以核实字典正确地存储了专辑的信息。

给函数make_album() 添加一个默认值为None 的可选形参,以便存储专辑包含的歌曲数。如果调用这个函数时指定了歌曲数,就将该值添加到表示专辑的字典中。调用这个函数,并至少在一次调用中指定专辑包含的歌曲数。

def make_album(name, album, num=None):
    album_name = {'name': name, 'album_name': album}
    if num:
        album_name['number'] = num
    else:
        album_name['number'] = 0
    return album_name
 
name1 = make_album('beijing', 'china', 5)
name2 = make_album('tokyo', 'japan', 10)
name3 = make_album('Washington', 'america')
print(name1)
print(name2)
print(name3)

输出:

{'name': 'beijing', 'album_name': 'china', 'number': 5}
{'name': 'tokyo', 'album_name': 'japan', 'number': 10}
{'name': 'Washington', 'album_name': 'america', 'number': 0}

练习8-8

用户的专辑 在为完成练习8-7编写的程序中,编写一个while 循环,让用户输入专辑的歌手和名称。获取这些信息后,使用它们来调用函数make_album() 并将创建的字典打印出来。在这个while 循环中,务必提供退出途径。

def make_album(name, album, num=None):
    album_name = {'name': name, 'album_name': album}
    if num:
        album_name['number'] = num
    else:
        album_name['number'] = 0
    return album_name

while True:
    
    name = input("Please input singer's name: ")
       
    if name == 'q':
        break
    
    print("\nenter 'q' at any time to quit: ")
    album = input("Please input album's name: ")
    if album == 'q':
        break
    album_name = make_album(name, album, 5)
    
    print(album_name)

输出:

Please input singer's name: beijing

enter 'q' at any time to quit: 
Please input album's name: china
{'name': 'beijing', 'album_name': 'china', 'number': 5}
Please input singer's name: tokyo

enter 'q' at any time to quit: 
Please input album's name: japan
{'name': 'tokyo', 'album_name': 'japan', 'number': 5}
Please input singer's name: q

练习8-9

消息 创建一个列表,其中包含一系列简短的文本消息。将该列表传递给一个名为show_messages() 的函数,这个函数会打印列表中的每条文本消息。

def pri_text(texts):
    for text in texts:
        print(text)
 
texts = ['show', 'person', 'country', 'day']
pri_text(texts)

输出:

show
person
country
day

练习8-10

发送消息 在你为完成练习8-9而编写的程序中,编写一个名为send_messages() 的函数,将每条消息都打印出来并移到一个名为sent_messages 的列表中。调用函数send_messages() ,再将两个列表都打印出来,确认正确地移动了消息。

def send_messages(send_message, sent_message ):
    while send_message:
        m = send_message.pop()
        sent_message.append(m)
        
    print(f"{send_message}")
    print(f"{sent_message}")
 
send_message = ['show', 'person', 'country', 'day']
sent_message = []
send_messages(send_message, sent_message)

输出:

[]
['day', 'country', 'person', 'show']

练习8-11

消息归档 修改你为完成练习8-10而编写的程序,在调用函数send_messages() 时,向它传递消息列表的副本。调用函数send_messages() 后,将两个列表都打印出来,确认保留了原始列表中的消息。

def send_messages(send_message, sent_message):
    while send_message:
        m = send_message.pop()
        sent_message.append(m)
 
    print(f"{send_message}")
    print(f"{sent_message}")
 
send_message = ['show', 'person', 'country', 'day']
sent_message = []
send_messages(send_message[:], sent_message[:])
print(f"{send_message}")
print(f"{sent_message}")

输出:

[]
['day', 'country', 'person', 'show']
['show', 'person', 'country', 'day']
[]

练习8-12

三明治 编写一个函数,它接受顾客要在三明治中添加的一系列食材。这个函数只有一个形参(它收集函数调用中提供的所有食材),并打印一条消息,对顾客点的三明治进
行概述。调用这个函数三次,每次都提供不同数量的实参。

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')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

输出:

Making a pizza with the following toppings:
- pepperoni

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

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

练习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('alice', 'harden',
                             location='xian',
                             filed='physics')
 
print(user_profile)

输出:

{'location': 'xian', 'filed': 'physics', 'first_name': 'alice', 'last_name': 'harden'}

练习8-14

汽车 编写一个函数,将一辆汽车的信息存储在字典中。这个函数总是接受制造商和型号,还接受任意数量的关键字实参。这样调用该函数:提供必不可少的信息,以及两个
名称值对,如颜色和选装配件。这个函数必须能够像下面这样进行调用:

car = make_car(‘subaru’, ‘outback’, color=‘blue’, tow_package=True)

打印返回的字典,确认正确地处理了所有的信息。

def make_car(manufacturer, model, **user_info):
    user_info['manufacturer'] = manufacturer
    user_info['model'] = model
    return user_info
 
car = make_car('subaru', 'outback', color='blue', two_package=True)
print(car)

输出:

{'color': 'blue', 'two_package': True, 'manufacturer': 'subaru', 'model': 'outback'}

练习8-15

打印模型 将示例printing_models.py中的函数放在一个名为printing_functions.py的文件中。在printing_models.py的开头编写一条import 语句,并修改该文件以使用导入的函数。

printing_models.py

def print_models(unprinted_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)

printing_functions.py

import printing_models as pf
 
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
 
pf.print_models(unprinted_designs, completed_models)
pf.show_completed_models(completed_models)

输出:

Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone case

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

练习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 *

练习8-17

函数编写指南 选择你在本章中编写的三个程序,确保它们遵循了本节介绍的函数编写指南。

你可能感兴趣的:(python,c#,开发语言)