例题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))
结果:
发现的问题:
- 记得传递参数
- 8-13
- 让参数变作为可选的,设置默认值为‘’空字符串
if amount:
album[‘amount’] = amount
然后输入什么值都行??? - 练习8.8
- 注意在什么时候用“”,什么时候用‘’
- 使用任意数量的关键字实参,可看做字典传进去,不要忘记.items()
调用时,注意‘关键字’不需要加引号。 - 8-14