8-8 用户的专辑:在为完成练习8-7编写的程序中,编写一个while 循环,让用户输入一个专辑的歌手和名称。获取这些信息后,使用它们来调用函数make_album(),并将创建的字典打印出来。在这个while 循环中,务必要提供退出途径。
Solution:
def make_album(singer, album_name, song_num=""):
"""make a dictionary of a album by singer, album name and song number"""
if song_num:
album = {'singer': singer, 'album name': album_name,
'song number': song_num}
else:
album = {'singer': singer, 'album name': album_name}
return album
active = True
while active:
Singer_name = input("Singer name: ")
Album_name = input("Album name: ")
Song_num = input("Song number: ")
Album = make_album(Singer_name, Album_name, Song_num)
print(Album)
while True:
repeat = input("Still have another album? Y/N\n")
if (repeat == "N"):
active = False
break
elif(repeat == "Y"):
print("Next one.\n")
break
else:
print("Wrong input. Please input again.\n")
Output:
Singer name: Azis
Album name: Diva
Song number:
{'singer': 'Azis', 'album name': 'Diva'}
Still have another album? Y/N
Y
Next one.
Singer name: Mayday
Album name: Second Bound
Song number: 16
{'singer': 'Mayday', 'album name': 'Second Bound', 'song number': '16'}
Still have another album? Y/N
djdj
Wrong input. Please input again.
Still have another album? Y/N
8-11 不变的魔术师:修改你为完成练习8-10而编写的程序,在调用函数make_great()时,向它传递魔术师列表的副本。由于不想修改原始列表,请返回修改后的列表,并将其存储到另一个列表中。分别使用这两个列表来调用show_magicians(),确认一个列表包含的是原来的魔术师名字,而另一个列表包含的是添加了字样“the Great”的魔术师名字。
Solution:
def show_megicians(_magicians):
"""magician's name"""
for magician in _magicians:
print("\t" + magician)
def make_great(_magicians):
"""the Great magician's name"""
size = len(_magicians)
while size:
_magicians[size-1] = "the Great " + _magicians[size-1]
size -= 1
return _magicians
magicians = ["Harry Potter", "Illyasviel von Einzbern"]
Great_magicians = make_great(magicians[:])
show_megicians(magicians)
show_megicians(Great_magicians)
Output:
Harry Potter
Illyasviel von Einzbern
the Great Harry Potter
the Great Illyasviel von Einzbern
8-14 汽车:编写一个函数,将一辆汽车的信息存储在一个字典中。这个函数总是接受制造商和型号,还接受任意数量的关键字实参。这样调用这个函数:提供必不可少的信息,以及两个名称—值对,如颜色和选装配件。这个函数必须能够像下面这样进行调用:
car = make_car('subaru', 'outback', color='blue', tow_package=True)
Solution:
def make_car(producer, _type, **car_info):
"""Make a dictionary to include all the information of a car"""
profile = {}
profile['producer'] = producer
profile['type'] = _type
for key, value in car_info.items():
profile[key] = value
return profile
car = make_car('subaru', 'outback', color='blue', tow_package=True)
print(car)
Output:
{'producer': 'subaru', 'type': 'outback', 'color': 'blue', 'tow_package': True}