美文网首页
11 函数进阶

11 函数进阶

作者: 陪伴_520 | 来源:发表于2019-01-05 11:18 被阅读0次

    向函数传递列表

    一个简单的示例 --- 向列表里的每一位问好!
    def greet_users(names):
        """向列表里的每位朋友问好!"""
    #下面是函数要做的事情
        for name in names:
            msg = "Hello, " + name.title() + "!"
            print(msg)
    #先定义一个列表,还记的这里的usernames是叫实参        
    usernames = ['zong hui', 'liu peipei', 'li guojian']
    #最后我们来调用这个函数greet_users()
    greet_users(usernames) 
    

    Result

    Hello, Zong Hui!
    Hello, Liu Peipei!
    Hello, Li Guojian!

    --- 模拟3D打印的制作过程
    def print_models(unprinted_designs, completed_models):
        """
        模拟打印每个设计,直到没有未打印的为止
        打印设计后,将其移至completeed_models列表   
        """ #这是对函数的说明,将产生一个函数说明问价
        while unprinted_designs:
            current_design = unprinted_designs.pop()#还记得pop()函数吗?它弹出列表元素
            
            #模拟根据设计制作3D打印的过程
            print("Printing model: " + current_design)
            completed_models.append(current_design)#还记得append()函数吗?它从列表末尾增加元素
    
    def show_completed_models(completed_models):
        """显示打印好的所以模型"""
        print("\nThe following models have been printed:")
        for completed_model in completed_models:
            print(completed_model)
            
    #下面假设未打印的模型列表
    unprinted_designs = ['plane', 'car', 'bicycle']
    #定义一个空列表,打印好的移至completed_models
    completed_models = []
    
    #下面调用第一个函数去处理
    print_models(unprinted_designs, completed_models)
    #再调用第二个函数去show
    show_completed_models(completed_models)
    
    ######这个小程序也给了我们一些启示:
    #一个函数只执行一项具体任务,例如此处模拟打印过程由一个函数完成,展示打印结果由另一个函数完成。   
    

    Result

    Printing model: bicycle
    Printing model: car
    Printing model: plane

    The following models have been printed:
    bicycle
    car
    plane

    以上的程序,未打印列表不会被保存,但是有时候我们却需要它做备案
    可以只向函数传递列表的副本 --- 还记得函数切片吗?
    #只需要要将上面调用函数时传递的实参稍作更改即可
    print_models(unprinted_designs[:], completed_models)
    #unprinted_designs[:]
    #只是将未打印列表的副本传递给了函数,也就是说原列表未改变
    
    (但是不推荐给函数传递列表副本,因为这会增加时间和内存,除非你有充分的理由需要创建副本)
    传递任意数量的实参
    #你可以向函数传递任意多的实参 --- 点披萨的程序
    def make_pizza(*toppings):
        """打印顾客所选择的配料"""
        print(toppings)
    
    #下面地调用这个函数
    make_pizza('pepperoni')
    make_pizza('mushroom', 'green peppers', 'extra cheese')
    
    #结果展示了不管输入几个实参,都被函数接收并打印
    #用 function( *形参)的形式定义一个可以接收任意数量实参的形参
    

    Result

    ('pepperoni',)
    ('mushroom', 'green peppers', 'extra cheese')

    为了让以上结果好看些,可以遍历一下列表 --- 把新函数记作make_pizza2()
    def make_pizza2(*toppings):
        """概述要制作的pizza"""
        print("\nMaking a pizza with the following toppings:")
        for topping in toppings:
            print("-" + topping)
    
    #下面地调用这个函数
    make_pizza2('pepperoni')
    make_pizza2('mushroom', 'green peppers', 'extra cheese')
    

    Result

    Making a pizza with the following toppings:
    -pepperoni

    Making a pizza with the following toppings:
    -mushroom
    -green peppers
    -extra cheese

    结合使用 位置实参和任意数量实参
    #点pizza时还需要制定pizza的尺寸 --- 我们假设顾客指定pizza的尺寸和配料
    def make_pizza(size, *toppings):
        """概述要制作的pizza"""
        print("\nMaking a " + str(size) + " pizza with the following toppings:")
        for topping in toppings:
            print("-" + topping)
            
    make_pizza(16, 'pepperoni')
    make_pizza(12, 'mushroom', 'green peppers', 'extra cheese')
    #函数的形参有两个,一个对应尺寸信息,一个是配料信息。注意要把任意形参放在最后
    

    Result

    Making a 16 pizza with the following toppings:
    -pepperoni

    Making a 12 pizza with the following toppings:
    -mushroom
    -green peppers
    -extra cheese

    使用任意数量的 关键字实参 --- 建立人物简介表的示例
    def build_profile(first, last, **user_info):    #profile是人物简介的意思
        """创建一个字典,其中包含我们知道的有关用户的一切信息"""
        #首先建立一个空字典,用于存储用户信息
        profile = {} 
        profile['first_name'] = first
        profile['last_name'] = last
        
        for key, value in user_info.items():#还记得items()函数吗?它遍历字典的键-值对
            profile[key] = value            #将键-值对加入字典中
            
        #最后我们把字典profile返回给函数
        return profile 
    #调用函数并输出结果
    user_profile = build_profile('zong', 'hui',
                                  location = 'shanghai',
                                  field = 'sleep')
    print(user_profile)
    
    #函数有一个形参 **info 它接收传递来的 键-值对
    

    Result

    {'first_name': 'zong', 'last_name': 'hui', 'location': 'shanghai', 'field': 'sleep'}

    0b651100d87b72cb8eb1885f3e8306a1.jpg

    相关文章

      网友评论

          本文标题:11 函数进阶

          本文链接:https://www.haomeiwen.com/subject/ccgkrqtx.html