您的位置:首页 > 编程语言 > Python开发

Python 从入门到实践 8-12 课后习题

2017-12-20 10:43 891 查看
8.12

三明治:编写一个函数,它接受顾客要在三明治中添加的一系列食材。这个

函数只有一个形参(它收集函数调用中提供的所有食材),并打印一条消息,对顾客点

的三明治进行概述。调用这个函数三次,每次都提供不同数量的实参。

def food(*toppings):
for topping in toppings:
print(topping.title())

food('pizza', 'nice', 'new')
food('banbana', 'apple', 'orange', 'out')
food('beautiful')


8.13

用户简介:复制前面的程序user_profile.py,在其中调用build_profile()来

创建有关你的简介;调用这个函数时,指定你的名和姓,以及三个描述你的键值对。

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('Xu', 'xz',personal_info={'age': '23','favorite': 'music','number': '6' }
)
print(user_profile)


8.14

汽车:编写一个函数,将一辆汽车的信息存储在一个字典中。这个函数总是接

受制造商和型号,还接受任意数量的关键字实参。这样调用这个函数:提供必不可少的

信息,以及两个名称—值对,如颜色和选装配件。这个函数必须能够像下面这样进行调用:

car = make_car('subaru', 'outback', color='blue', tow_package=True)

打印返回的字典,确认正确地处理了所有的信息。

def car_information(brand,name, **car_info):
"""创建一个字典,其中包含我们知道的有关用户的一切"""
car = {}
car['brand'] = brand
car['name'] = name
for key, value in car_info.items():
car[key] = value
return car

user_profile = car_information('subaru', 'outback',car_info={'color': 'blue','two_package': 'True','place': 'japan' }
)
print(user_profile)


凑巧的是我也知道这个车,名字叫斯巴鲁,傲虎。当时觉得很神奇,为什么outback是傲虎,就是现在我也不知道。不过确实很漂亮!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: