高級編程技術(Python)作業8

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}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章