Python 函数

作者: 赵者也 | 来源:发表于2018-01-25 14:36 被阅读6次
    1. 函数
    def describe_pet(animal_type, pet_name):
        print("\nI have a " + animal_type + ".")
        print("My " + animal_type + "'s name is " + pet_name.title() + ".")
    
    
    describe_pet('hamster', 'harry')
    describe_pet('dog', 'willie')
    
    1. 关键字实参
    def describe_pet(animal_type, pet_name):
        print("\nI have a " + animal_type + ".")
        print("My " + animal_type + "'s name is " + pet_name.title() + ".")
    
    
    describe_pet(pet_name='harry', animal_type='hamster')
    
    1. 默认值
    def describe_pet(pet_name, animal_type="dog"):
        print("\nI have a " + animal_type + ".")
        print("My " + animal_type + "'s name is " + pet_name.title() + ".")
    
    
    describe_pet(animal_type='hamster', pet_name='harry')
    describe_pet(pet_name='jim')
    

    实例输出:

    默认值
    1. 返回简单值
    def get_formatted_name(first_name, last_name):
        full_name = first_name + ' ' + last_name
        return full_name.title()
    
    
    musician = get_formatted_name('jim', 'hendrix')
    print(musician)
    
    1. 让实参变成可选的
    def get_formatted_name(first_name, last_name, middle_name=""):
        if middle_name:
            full_name = first_name + ' ' + middle_name + ' ' + last_name
        else:
            full_name = first_name + ' ' + last_name
        return full_name.title()
    
    
    musician = get_formatted_name('john', 'hooker')
    print(musician)
    
    musician = get_formatted_name('john', 'hooker', "lee")
    print(musician)
    
    1. 传递列表
    def greet_users(names):
        for name in names:
            print("Hello, " + name.title() + "!")
    
    
    user_names = ["toby", "tina", "john"]
    greet_users(user_names)
    
    1. 在函数中修改列表
    def print_models(designs, models):
        while designs:
            current_design = designs.pop()
            print("Printing model: " + current_design)
            models.append(current_design)
    
    
    def show_completed_models(models):
        print("\nThe following models have been printed:")
        for completed_model in models:
            print(completed_model)
    
    
    unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
    completed_models = []
    
    print_models(unprinted_designs, completed_models)
    show_completed_models(completed_models)
    
    1. 禁止函数修改列表
    def print_models(designs, models):
        while designs:
            current_design = designs.pop()
            print("Printing model: " + current_design)
            models.append(current_design)
    
    
    def show_models(models):
        print("\nThe following models have been printed:")
        for completed_model in models:
            print(completed_model)
    
    
    unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
    completed_models = []
    
    print_models(unprinted_designs[:], completed_models)  # 使用切片将副本传入
    show_models(completed_models)
    print(unprinted_designs)
    
    1. 传递任意数量的实参
    def make_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')
    
    1. 结合使用位置实参和任意数量实参
    def make_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')
    
    1. 使用任意数量的关键字实参
    def build_profile(first, last, **user_info):
        profile = {"first_name": first, "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:")
    print(user_profile)
    

    输出结果:

    使用任意数量的关键字实参
    1. 导入整个模块

    定义 pizza.py 文件:

    pizza.py 文件

    使用整个模块:

    使用整个模块
    1. 导入特定的函数
    from pizza import make_pizza
    
    make_pizza(16, 'pepperoni')
    make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
    
    1. 使用 as 给函数指定别名
    from pizza import make_pizza as mp
    
    mp(16, 'pepperoni')
    mp(12, 'mushrooms', 'green peppers', 'extra cheese')
    
    1. 使用 as 给模块指定别名
    import pizza as mp
    
    mp.make_pizza(16, 'pepperoni')
    mp.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
    
    1. 导入模块中的所有函数
    from pizza import *
    
    make_pizza(16, 'pepperoni')
    make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
    

    本文参考自 《Python 编程:从入门到实践

    相关文章

      网友评论

        本文标题:Python 函数

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