函數與字典,可選參數和while語句結合的簡單應用
阿新 • • 發佈:2018-03-23
函數python函數可以與各種語句相結合,以達到提高效率簡化流程的目的:
- 通過函數創建字典
eg. 將歌手與專輯對應,並儲存在字典當中
def make_ablum(name, album): """返回整潔的字典格式""" album_details = {‘singer‘: name, ‘album‘: album_name} return album_details #已經定義好了字典,現在可以輸入幾個對應值來檢測 album_details_1 = make_album(‘Jay‘, ‘Fantasy‘) album_details_2 = make_album(‘Taylor Swift‘, ‘Style‘) album_details_3 = make_album(‘elva‘, ‘the fifth ave‘) print(album_details_1) print(album_details_2) print(album_details_3)
2 在函數中添加可選參數,也就是說,如果添加,則會顯示;若不添加,則自動忽略。
只需要用if語句就可以實現這個功能
eg.在上面的歌手與專輯的對應中,添加個歌曲數量的統計
def make_album(name, album_name, number_of_songs = ""): #number_of_songs 先用空字符代替 """將歌曲數設置為可選參數""" album_details = {‘singer‘: name, ‘album‘: album_name} if number_of_songs: album_details[‘number of songs‘] = number_of_songs #只要填入歌曲數,則if語句為真,相應的,會在字典中添加 return album_details #定義好以後,可以分別用含歌曲數和不含的兩組值來測試 detail_1 = make_album(‘Jay‘, ‘Fantasy‘) detail_2 = make_album(‘Taylor Swift‘, ‘Style‘, ‘1‘) print(detail_1) print(detail_2)
3 除了與if語句相結合,同樣也可以與while語句結合,比如下面的例子。通過和while結合,通過用戶自己的輸入,編寫好字典的相關信息。並加入指示,使用戶可以停止該循環:
def make_album(name, album_name, number_of_songs): """將歌曲數設置為可選參數,在用while語句通過用戶輸入調用""" album_details = {‘singer‘: name, ‘album‘: album_name} if number_of_songs: album_details[‘number of songs‘] = number_of_songs return album_details #函數定義好以後,就可以與while語句相結合 while True: print("\nPlease tell me the details of your favorite album:") print("(enter ‘q‘ at any time to quit)") name = input("Singer‘s name: ") if name == "q": break #break的使用可以使用戶操作停止該循環 album_name = input("Favorite album:") if album_name == "q": break number_of_songs = input("How many songs in the album?") if number_of_songs == "q": break album_details = make_album(name, album_name, number_of_songs) print("Thanks for the following information!") print(album_details)
函數與字典,可選參數和while語句結合的簡單應用