defmake_pizza(*toppings):"""概述要做的比萨"""print("\nMaking a pizza with the following toppings: ")for topping in toppings:print("- "+ topping)
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
Making a pizza with the following toppings:
- pepperoni
Making a pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
defmake_pizza(size,*toppings):print("\nMaking a "+str(size)+"-inch pizza with the following toppings:")for topping in toppings:print("- "+ topping)
make_pizza(16,'pepperoni')
make_pizza(12,'mushrooms','green peppers','extra cheese')
Making a 16-inch pizza with the following toppings:
- pepperoni
Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
使用任意数量的关键字实参
两个星号创建了一个空字典,将收到的所有名称-值对都封装到这个字典中
# 案例defbuild_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)
# 1.三明治# 编写一个函数,它接受顾客要在三明治中添加的一系列食材。这个函数只有一个形参(它收集函数调用中提供的所有食材),并打印一条消息,对顾客# 点的三明治进行概述。调用这个函数三次,每次都提供不同数量的实参defadd_sandwich(*foods):print("\n I'll make you a great sandwich: ")for food in foods:print("....adding "+ food +" to your sandwich.")print("Your sandwich is ready!")
add_sandwich('roast beef','cheddar cheese','lettuce','honey dijon')
add_sandwich('turkey','apple slices','honey mustard')
add_sandwich('peanut butter','strawberry jam')
I'll make you a great sandwich:
....adding roast beef to your sandwich.
....adding cheddar cheese to your sandwich.
....adding lettuce to your sandwich.
....adding honey dijon to your sandwich.
Your sandwich is ready!
I'll make you a great sandwich:
....adding turkey to your sandwich.
....adding apple slices to your sandwich.
....adding honey mustard to your sandwich.
Your sandwich is ready!
I'll make you a great sandwich:
....adding peanut butter to your sandwich.
....adding strawberry jam to your sandwich.
Your sandwich is ready!
# 2.用户简介# 在其中调用 build_profile() 来创建有关你的简介;调用这个函数时,指定你的名和姓,以及三个描述你的键 - 值对。defbuild_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('li','yege',
height ='170cm',
weight ='70kg',
hobby ='basketball',)print(user_profile)
# 3.汽车# 编写一个函数,将一辆汽车的信息存储在一个字典中。这个函数总是接受制造商和型号,还接受任意数量的关键字实参。这样调用这个函数:提供必不可# 少的信息,以及两个名称 — 值对,如颜色和选装配件。这个函数必须能够像下面这样进行调用defbuild_cars(made_address, model,**user_info):
cars ={}
cars['address']= made_address
cars['model']= model
for key,value in user_info.items():
cars[key]= value
print(cars)
build_cars('china','big',color ='blue', name ='changcheng')