高階程式設計技術(Python)作業8
阿新 • • 發佈:2019-02-08
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}