python第七次練習

例題8-13 用戶簡介

  描述:任意數量的關鍵字實參創建用戶簡介,名和姓加描述鍵值對。
  代碼:

def build_profile(first, last, **user_info):
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key,value in user_info.items():
        profile[key] = value
    return profile
user_profile = build_profile('albert', 'einstein', 
                             location='princeton',
                             field='physics')
print(user_profile)
my_profile = build_profile('ponyo', 'hu',
                           location='Guangzhou',
                           age='20',
                           gender='female')
print(my_profile)

  結果:
這裏寫圖片描述

例題8-12 三明治

  描述:任意數量的實參,只有一個形參(收集所有食材)。
  代碼:

def make_sandwich(*toppings):
    print("\nMaking a sandwich with the following toppings:")
    for topping in toppings:
        print("-" + topping)
make_sandwich("beef", "mushroom" ,"onions")
make_sandwich("beef")
make_sandwich("beef", "onions")

  結果:
這裏寫圖片描述

例題8-8 用戶的專輯

  描述:使用while輸入歌手和專輯名稱,返回字典。
  代碼:

def make_album(name, album_name, amount = ''):
    album = {'name': name, 'album_name': album_name}
    if amount:
        album['amount'] = amount
    return album
print(make_album('Jay Chou', 'Jay'))
print(make_album('coldplay', 'Parachutes'))
print(make_album('The Chainsmokers', 'Bouquet', 5))

  結果:
這裏寫圖片描述

發現的問題:

  1. 記得傳遞參數
  2. 8-13
  3. 讓參數變作爲可選的,設置默認值爲‘’空字符串
    if amount:
    album[‘amount’] = amount
    然後輸入什麼值都行???
  4. 練習8.8
  5. 注意在什麼時候用“”,什麼時候用‘’
  6. 使用任意數量的關鍵字實參,可看做字典傳進去,不要忘記.items()
    調用時,注意‘關鍵字’不需要加引號。
  7. 8-14
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章