python学习:函数(一)

举例:

def greet_user():
    """显示简单的问候语"""
    print("Hello!")

greet_user()

一、函数定义:

1、使用关键字:def 来定义一个一个python函数。

2、函数名:       greet_user为函数名。在python中使用下划线 ”_" 来分离不同的单词,而不是使用java中常用的驼峰表示法。

3、函数参数:    在函数名后的括号中添加函数的形参。

4、函数定义结尾:使用冒号 “ :”来结尾。

5、函数体:        在冒号后面的为函数体。函数体需要使用缩进来区分是否为函数体,而不是使用括号的方式来界定。

6、文档字符串: 三对双引号为文档字符串(docstring),标记函数的用途。

二、传递参数:

1、传递位置实参:      要求实参和形参的位置保持一致。

2、传递关键字实参:   每个参数都由变量名和值构成。

3、还可以使用列表和字典。

4、默认值:函数定义时可以给每个形参赋默认值,如果函数调用时,没有给该形参赋值,则该值为默认值。

                     需要注意的是,默认值必须在后面(可以是多个)。

位置实参:

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')

关键字实参:

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(animal_type='hamster', pet_name='harry')

三、返回值:

可使用return 语句将值返回到调用函数的代码行。
 

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('jimi', 'hendrix', 'lee')
print(musician)

四、传递列表:

def greet_users(names):
    """向列表总的每位用户都发出简单的问候"""
    print()
    for name in names:
        msg = "Hello, " + name.title() + "!"
        print(msg)

usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)

五、函数修改列表:

def print_models(unprinted_designs, completed_models):
    """
    模拟打印每个设计, 直到没有未打印的设计为止
    打印每个设计后, 都将其移到列表completed_models中
    """
    while unprinted_designs:
        current_design = unprinted_designs.pop()

        #模拟根据设计制作3D打印模型的过程
        print("Printing model:" + current_design)
        completed_models.append(current_design)

def show_completed_models(completed_models):
    """显示打印好的所有模型"""
    print("\nThe following models have been printed:")
    for completed_model in completed_models:
        print(completed_model)

unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []

print_models(unprinted_designs,completed_models)
show_completed_models(completed_models)

六、禁止函数修改列表:

可以向函数传递列表的副本而非原件来实现禁止函数修改列表。

python使用切片 listname[:] 来创建副本。

print_models(unprinted_designs[:], completed_models)

七、传递任意数量的实参:

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')

其中*toppings中的星号让Python创建一个名为toppings 的空元组, 并将收到的所有值都封装到这个元组中。

Python将实参封装到一个元组中, 即便函数只收到一个值也如此。

八、结合使用位置实参和任意数量实参:

如果要让函数接受不同类型的实参, 必须在函数定义中将接纳任意数量实参的形参放在最后。 Python先匹配位置实参和关键字实参, 再将余下的实参都收集到最后一个形参中。
 

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')

九、使用任意数量的关键字实参:

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('albert', 'einstein',
                             location = 'princeton',
                                field = 'physics')
print(user_profile)

其中:形参**user_info 中的两个星号让Python创建一个名为user_info 的空字典, 并将收到的所有名称—值对都封装到这个字典中。

发布了4 篇原创文章 · 获赞 3 · 访问量 368

猜你喜欢

转载自blog.csdn.net/Wolfswood/article/details/104344476
今日推荐