Python编程:从入门到实践 (第八章习题)

#8-1 消息:编写一个名为 display_message()的函数,它打印一个句子,指出你在本章学的是什么。
# 调用这个函数,确认显示的消息正确无误。
def display_message():
   print("In the chapter 8, we will learn how to define a function!")

display_message()

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

def favorite_book(title):
   """favorite books"""
   print("One of my favorite books is " +title.title()  +".")

favorite_book("animal farm")

#8-3 T 恤:编写一个名为 make_shirt()的函数,它接受一个尺码以及要印到 T 恤上的字样。
# 这个函数应打印一个句子,概要地说明 T 恤的尺码和字样。
# 使用位置实参调用这个函数来制作一件 T 恤;再使用关键字实参来调用这个函数。


def make_shirt(size,letter_sample):
   """information of size and letter sample"""
   print("\nThis t-shirt is in size " + size.upper() + ", and please print " + letter_sample.upper() + " on it.")


make_shirt("l","i love you")
make_shirt(letter_sample= "love",size="x")

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


def make_shirt(size="L",letter_sample="I love Python"):
   """information of size and letter sample"""
   print("\nPlease make a t-shirt is in size " + size.upper() + ", and print " + letter_sample + " on it.")


make_shirt()
make_shirt(size="xl")
make_shirt("m",'Love')

#8-5 城市:编写一个名为 describe_city()的函数,它接受一座城市的名字以及该城市所属的国家。
# 这个函数应打印一个简单的句子,如 Reykjavik is in Iceland。给用于存储国家的形参指定默认值。
# 为三座不同的城市调用这个函数,且其中至少有一座城市不属于默认国家。


def describe_city(city,country='china'):
   print("\n" + city.title() + " is in " + country.title() +".")


describe_city("shanghai")
describe_city("hongkong")
describe_city("paris","france")

#8-6 城市名:编写一个名为 city_country()的函数,它接受城市的名称及其所属的国家。
# 这个函数应返回一个格式类似于下面这样的字符串:"Santiago, Chile"
# 至少使用三个城市 - 国家对调用这个函数,并打印它返回的值


def country_city(city,country):
   city_country = city + ", " + country
   return city_country.title()


city_1 = country_city("santiago","chile")
print(city_1 )
city_2 = country_city("shanghai","china")
print(city_2)
city_3 = country_city("tokuyo","Janpa")
print(city_3)

#8-7 专辑:编写一个名为 make_album()的函数,它创建一个描述音乐专辑的字典。
# 这个函数应接受歌手的名字和专辑名,并返回一个包含这两项信息的字典。
# 使用这个函数创建三个表示不同专辑的字典,并打印每个返回的值,以核实字典正确地存储了专辑的信息。
# 给函数 make_album()添加一个可选形参,以便能够存储专辑包含的歌曲数。
# 如果调用这个函数时指定了歌曲数,就将这个值添加到表示专辑的字典中。
# 调用这个函数,并至少在一次调用中指定专辑包含的歌曲数。


def make_album(singer_name, album_name, song_number=""):
   singer_album = {
      "Singer's name": singer_name.title(),
      "Album name": album_name.title(),
   }
   if song_number:
      singer_album["song numbers"] = song_number
   return singer_album


singer_01 = make_album("leslie cheung", "red")
print(singer_01)
singer_02 = make_album("david bowie", "aladdin sane", 10)
print(singer_02)
singer_03 = make_album("hugh laurie", "let them talk", song_number=10)
print(singer_03)

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

def make_album(singer_name, album_name, song_number=""):
   singer_album = {
      "Singer's name": singer_name.title(),
      "Album name": album_name.title(),
   }
   return singer_album
while True:
   print("\nWhat is your favorite singer's name?")
   print("What's his/her alblum do you like most?")
   print("(You can quit at any time when you enter 'quit'.)")
   user_singer_name = input("Singer's name:")
   if user_singer_name == "quit":
      break
   user_album_name = input("Favorite alblum:")
   if user_album_name == "quit":
      break

   singer_album = make_album(user_singer_name, user_album_name)
   print("The information about your favourite singer and album, as following: ")
   print(singer_album)

#8-9 魔 术 师 : 创 建 一 个 包 含 魔 术 师 名 字 的 列 表 ,
# 并 将 其 传 递 给 一 个 名 为show_magicians()的函数,这个函数打印列表中每个魔术师的名字。

def show_magicians(magician_names): #定义一个函数show_magicians(),形参是括号里的magician_names,它是一个列表
   for magician_name in magician_names: #遍历magician_names这个参数列表里的每一个元素
      print(magician_name.title()) #打印出元素且首字母大写


magician_names = ['treya', 'anna', 'eric'] #这里给出实参,实参是一个列表
show_magicians(magician_names) #调用函数show_magicians() (括号里填写调用的实际参数)

#8-10 了不起的魔术师:在你为完成练习 8-9 而编写的程序中,
# 编写一个名为make_great()的函数,对魔术师列表进行修改,在每个魔术师的名字中都加入字样“the Great”。
# 调用函数 show_magicians(),确认魔术师列表确实变了。

def show_magicians(magician_names):  #定义一个函数show_magicians(),形参是括号里的magician_names,它是一个列表
   for magician_name in magician_names:
      print(magician_name.title())


def make_great(magician_names):  #定义另一个函数make_great(),它的形参是也是magician_names列表
   for magician_name in magician_names: #遍历列表中的每个元素
      great_name = "The Great " + magician_name.title() #修改形参里的元素,修改后的新元素叫great_name
      print(great_name) # 打印出所有的 great-name


magician_names = ['treya', 'anna', 'eric']
show_magicians(magician_names) #调用函数:展示魔术师的名字
make_great(magician_names) # 调用函数:修改后魔术师的名字

#8-11 不变的魔术师:修改你为完成练习 8-10 而编写的程序,
# 在调用函数 make_great()时,向它传递魔术师列表的副本。
# 由于不想修改原始列表,请返回修改后的列表,并将其存储到另一个列表中。
# 分别使用这两个列表来调用 show_magicians(),
# 确认一个列表包含的是原来的魔术师名字,而另一个列表包含的是添加了字样“the Great”的魔术师名字。

def show_magicians(magician_names):
   for magician_name in magician_names:
      print(magician_name.title())


def make_great(magician_names):
   for magician_name in magician_names:
      great_name = "The Great " + magician_name.title()
      great_names.append(great_name) #将修改后的名字,添加到great-names列表中
      print(great_name)


magician_names = ['treya', 'anna', 'eric']
great_names = [] #修改后的列表

show_magicians(magician_names)

make_great(magician_names[:]) #调用魔术师列表的副本

show_magicians(great_names) #以修改后的列表,调用函数

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

def orders(*toppings):
   print("\nWe will add these toppings: ")
   for topping in toppings:
      print("-" + topping)


orders('cheese')
orders('green pepper', 'cheese')
orders("apple", 'pineapple', 'cheese')

# 8-13 用户简介 : 复制前面的程序user_profile.py, 在其中调用build_profile() 来创建有关你的简介;
# 调用这个函数时, 指定你的名和姓, 以及三个描述你的键-值对。

def build_profile(first, last, **user_info): #两个星号的意思是创建一个名为 user_info的字典。
   profile = {}
   profile['first_name'] = first
   profile['last_name'] = last
   for key, value in user_info.items(): #遍历user_info字典中的每对键值
      profile[key] = value
   return profile  #以profile={}的形式返回值


user_profile = build_profile('treya','zheng', location='chengdu', field='english') #调用函数
print(user_profile)
user_profile = build_profile('treya','zheng', food='apple', vegitable='tomato') #调用函数
print(user_profile)
user_profile = build_profile('treya','zheng', spring='summer', animails='cat') #调用函数
print(user_profile)



# 8-14 汽车 : 编写一个函数, 将一辆汽车的信息存储在一个字典中。 这个函数总是接受制造商和型号, 还接受任意数量的关键字实参。
# 这样调用这个函数: 提供必不可少的信息, 以及两个名称—值对, 如颜色和选装配件。 这个函数必须能够像下面这样进行调用:
# car = make_car('subaru', 'outback', color='blue', tow_package=True)
# 打印返回的字典, 确认正确地处理了所有的信息。


def car_info(manufacture, model, **other_info):
   all_info = {}
   all_info["Manufacture"] = manufacture
   all_info["Model"] = model
   for key, value in other_info.items():
      all_info[key] = value
   return all_info


car_01 = car_info('sabaru', 'outback', color="blue", tow_package=True)
print(car_01)

#8-15 打印模型:将示例 print_models.py 中的函数放在另一个名为 printing_ functions.py 的文件中;
# 在 print_models.py 的开头编写一条 import 语句,并修改这个文件以使用导入的函数。
import print_models

unprinted_designs = ['iphone case','robot pendant','dodecahedron']
completed_models = []

print_models.print_models(unprinted_designs, completed_models)
print_models.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 *

#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 *

import all_car_info

car_01 = all_car_info.car_info('sabaru', 'outback', color="blue", tow_package=True)
print(car_01)

from all_car_info import car_info

car_01 = all_car_info.car_info('sabaru', 'outback', color="blue", tow_package=True)

print(car_01)
from all_car_info import car_info as information

car_01 = information('sabaru', 'outback', color="blue", tow_package=True)
print(car_01)

import all_car_info  as all_information

car_01 = all_information.car_info('sabaru', 'outback', color="blue", tow_package=True)
print(car_01)

from magic import *

show_magicians(magician_names)
make_great(magician_names)





















猜你喜欢

转载自blog.csdn.net/Treyaa/article/details/80342968