python函数--小任务5

8-12 三明治:编写一个函数,它接受顾客要在三明治中添加的一系列食材。这个函数只有一个形参(它收集函数调用中提供的所有食材),并打印一条消息,对顾客点的三明治进行概述。调用这个函数三次,每次都提供不同数量的实参。

 



def make_sandwiches(*ingredients):
    """在三明治中添加食材"""
    print("I'll add these in your sandwich:")
    for ingredient in ingredients:
        print('-'+ingredient)
#调用函数
make_sandwiches('egg','bacon')
make_sandwiches('banana')
make_sandwiches('egg','lettuce','ham')

 运行结果:

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('pip','awesome',
    family_members='4',
    girl_friend='no')
print(user_profile)

 调用函数时,形参**user_info让python创建一个名为user_info的空字典,并将收到的键值对封装进这个字典,似乎默认输入的“键”是字符串。

运行结果:

 8-14 汽车:编写一个函数,将一辆汽车的信息存储在一个字典中。这个函数总是接受制造商和型号,还接受任意数量的关键字实参。这样调用这个函数:提供必不可少的信息,以及两个名称—值对,如颜色和选装配件。这个函数必须能够像下面这样进行调用:

car = make_car('subaru', 'outback', color='blue', tow_package=True)
打印返回的字典,确认正确地处理了所有的信息。

 和上一个一样的。



def car_information(manufacturer,model,**car_info):
    """创建一个了解汽车信息的字典"""
    profile={}
    profile['manufacturer']=manufacturer
    profile['model']=model
    for key,value in car_info.items():
        profile[key]=value
    return profile

car_profile=car_information('subaru','outback',
    color='red',
    tow_package=True)
print(car_profile)

运行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Awesome╮(﹀_﹀)╭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值