python学习7:函数

python学习7:函数

函数是带名字的代码块,用于完成具体的工作。要执行函数定义的特定任务,可调用该函数。

1 定义函数

下面是一个打印问候语的简单函数。

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

greet_user()

结果:

Hello!

使用关键字def来告诉python,要定义一个函数,向python指出了函数名,还可能在圆括号内指出函数为完成任务需要什么样的信息,最后,定义以冒号结尾。

1.1 向函数传递信息

def greet_user(username):
    """显示简单的问候语"""
    print(f"Hello!,{username.title()}")

greet_user('jesse')

结果

Hello!,Jesse

2 传递实参

向函数传递实参的方式很多:

  • 位置实参,要求实参顺序与形参顺序相同;
  • 关键字实参,每个实参都由变量名和值组成;
  • 列表和字典

2.1 位置实参

def describe_pet(animal_type, pet_name):
    """显示宠物的信息"""
    print(f"\nI have a {animal_type}.")
    print(f"My {animal_type}'s name is {pet_name.title()}.")

describe_pet('hamster', 'harry')

结果:

I have a hamster.
My hamster's name is Harry.
  • 多次调用函数
describe_pet('hamster', 'harry')
describe_pet('dog', 'willie')

在函数中,可使用任意数量的位置实参,python将按顺序将函数调用中的实参关联到函数定义中的形参。

  • 位置实参的顺序很重要

2.2 关键字实参

关键字实参是传递给函数的名称值对。直接在实参中将名称和值关联起来,所以向函数传递实参时不会混淆。

def describe_pet(animal_type, pet_name):
    """显示宠物的信息"""
    print(f"\nI have a {animal_type}.")
    print(f"My {animal_type}'s name is {pet_name.title()}.")
    
describe_pet(pet_name='harry', animal_type='hamster')

结果:

I have a hamster.
My hamster's name is Harry.

关键字实参的顺序无关紧要,因为python知道各个值该付给哪个形象,使用时务必准确指定函数定义中的形参名。

2.3 默认值

在编写函数时,可给每个形参指定默认值。在调用函数中给形参提供了实参时,python将使用指定的实参值;否则,将使用默认的形参值。

def describe_pet(pet_name,animal_type='dog'):
    """显示宠物的信息"""
    print(f"\nI have a {animal_type}.")
    print(f"My {animal_type}'s name is {pet_name.title()}.")
    
describe_pet('willie')

结果:

I have a dog.
My dog's name is Willie.
  • 注意,在这个函数的定义中,修改了形参的排列顺序。因为给animal_type指定了默认值,无需通过实参来指定动物类型,所以在函数调用中只包含一个实参,然而,python将该实参视为位置实参,如果函数调用只包含宠物的名字,这个实参将关联到函数定义中的第一个形象,所以要将pet_name放在形参列表开头。

2.4 等效的函数调用

针对def describe_pet(pet_name,animal_type='dog'),在任何情况下都必须给pet_name提供实参,也可采用关键字方式。如果要描述的动物不是小狗,还必须在函数调用中给animal_type提供实参。同样指定该实参时可采用位置方式,也可采用关键字方式。

3 返回值

函数并非总是直接显示输出,它还可以处理一些数据,并返回一个或一组值。可使用return语句将值返回到调用函数的代码行。

3.1 返回简单值

def get_formatted_name(first_name, last_name):
    """返回整洁的姓名"""
    full_name = f"{first_name} {last_name}"
    return full_name.title()

musician = get_formatted_name('jimi', 'hendrix')
print(musician)

结果:

Jimi Hendrix

调用返回值的函数,需要提供一个变量,以便将返回的值赋给它。

3.2 返回字典

函数可返回任何类型的值,包括列表和字典等较复杂的数据结构。

def build_person(first_name, last_name):
    """返回一个字典,其中包含有关一个人的信息。"""
    person = {'first': first_name, 'last': last_name}
    return person

musician = build_person('jimi', 'hendrix')
print(musician)

结果:

{'first': 'jimi', 'last': 'hendrix'}

可以拓展该函数,使其接受可选值,如:

def build_person(first_name, last_name, age=None):
    """返回一个字典,其中包含有关一个人的信息。"""
    person = {'first': first_name, 'last': last_name}
    if age:
        person['age'] = age
    return person

musician = build_person('jimi', 'hendrix', age=27)
print(musician)

结果:

{'first': 'jimi', 'last': 'hendrix', 'age': 27}

3.3 结合使用函数和while循环

def get_formatted_name(first_name, last_name):
    """返回整洁的姓名"""
    full_name = f"{first_name} {last_name}"
    return full_name.title()

# 无限循环
while True:
    print("\nPlease tell me your name:")
    f_name = input('First name:')
    l_name = input('Last name:')

    formatted_name = get_formatted_name(f_name, l_name)
    print(f"\nHello,{formatted_name}!")

结果:

Please tell me your name:
First name:Liu
Last name:Yang

Hello,Liu Yang!

Please tell me your name:
First name:

while循环定义一个退出条件,每次提示用户输入时,都应该提供退出途径。

def get_formatted_name(first_name, last_name):
    """返回整洁的姓名"""
    full_name = f"{first_name} {last_name}"
    return full_name.title()

# 无限循环
while True:
    print("\nPlease tell me your name:")
    print("(enter 'q' at any time to quit)")
    f_name = input('First name:')
    if f_name == 'q':
        break
    l_name = input('Last name:')
    if l_name == 'q':
        break

    formatted_name = get_formatted_name(f_name, l_name)
    print(f"\nHello,{formatted_name}!")

结果:

Please tell me your name:
(enter 'q' at any time to quit)
First name:Liu
Last name:Yang

Hello,Liu Yang!

Please tell me your name:
(enter 'q' at any time to quit)
First name:q

4 传递函数

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

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

结果:

Hello,Hannah!
Hello,Ty!
Hello,Margot!

4.1 在函数中修改列表

将列表传递给函数后,函数可以对其进行修改,在函数中对列表的任何操作都是永久性的。

# 编写两个函数
def print_models(unprinted_designs, completed_models):
    """模拟打印每个设计,知道没有未打印的设计为止,打印每个设计后都将其移到空列表中"""
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        print(f"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 = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)

结果:

printing model:dodecahedron
printing model:robot pendant
printing model:phone case

The following models have been printed:
dodecahedron
robot pendant
phone case

使用了函数后,程序更加容易拓展和维护,每个函数只负责一项具体的工作。

4.2 禁止函数修改列表

可向函数传递列表的副本而非原件,这样,函数所作的任何修改都只影响副本,而原件不受影响。
切片表示法[:]创建列表的副本,如function_name(list_name_[:]),刚才的例子可改成:print_models(unprinted_designs[:],completed_models)

5 传递任意数量的实参

有时,预先不知道函数需要接受多少个实参,但python可以允许函数从调用语句中收集任意数量的实参。

def make_pizza(*toppings):
    """打印顾客点的所有配料"""
    print(toppings)

make_pizza('pepperoni')
make_pizza('mushroom', 'extra cheese')

结果:

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

形参名*topping中的星号让python创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中。
注意:python将实参封装到一个元组中,即便函数只收到一个值。

5.1 结合使用位置实参和任意数量实参

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

def make_pizza(size, *toppings):
    """概述要制作的比萨"""
    print(f"\nMaking a {size}-inch pizza with the following toppings:")
    for topping in toppings:
        print(f"-{topping}")

make_pizza(16, 'pepperoni')
make_pizza(12, 'mushroom', 'extra cheese')

结果:

Making a 16-inch pizza with the following toppings:
-pepperoni

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

5.2 使用任意数量的关键字实参

接受任意数量的实参,但预先不知道传递给函数的会是什么样的信息。可将函数编写成能够接受任意数量的键值对。

def build_profile(first, last, **user_info):
    """创建一个字典,其中包含我们知道的有关用户的一切。"""
    user_info['first_name'] = first
    user_info['last_name'] = last
    return user_info

user_profile = build_profile('albert', 'einstein', location='princeton', field='physics')
print(user_profile)

结果:

{'location': 'princeton', 'field': 'physics', 'first_name': 'albert', 'last_name': 'einstein'}

形参**user_info中的两个星号让python创建一个名为user_info的空字典,并将收到的有名称的值对放到这个字典中,用于收集任意数量的关键字实参。在这个函数中,可以像访问其他字典那样访问user_info中的名称值对。

6 将函数存储在模块中

可以将函数存储在模块的独立文件中,再将模块导入到主程序中。import语句允许在当前运行的程序文件中使用模块中的代码。

6.1 导入整个模块

编写import语句并在其中指定模块名,可在程序中使用该模块的所有函数。

def make_pizza(size, *toppings):
    """概述要制作的比萨"""
    print(f"\nMaking a {size}-inch pizza with the following toppings:")
    for topping in toppings:
        print(f"-{topping}")
import pizza

pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushroom', 'green peppers')

结果:

Making a 16-inch pizza with the following toppings:
-pepperoni

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

6.2 导入特定的函数

可以导入模块中的特定函数,语法如:from module_name import function_name;通过逗号分隔函数名,可根据需要从模块中导入任意数量的函数:from module_name import function_0,function_1
上述函数将类似这样:

from pizza import make_pizza

make_pizza(16, 'pepperoni')
make_pizza(12, 'mushroom', 'green peppers')

使用这种语法时,调用函数时无须使用句点。由于在import语句中显式导入函数make_pizza(),调用时只需指定其名称即可。

6.3 使用as给函数指定别名

给函数指定外号,需要在导入它时指定,使用关键字as将函数重命名为指定的别名。

from pizza import make_pizza as mp

mp(16, 'pepperoni')
mp(12, 'mushroom', 'green peppers')

6.4 使用as给模块指定别名

如:import modeule_name as mn

6.5 导入模块中的所有函数

使用==星号(*)==运算符可让python导入模块中的所有函数:

from pizza import *

make_pizza(16, 'pepperoni')
make_pizza(12, 'mushroom', 'green peppers')

该星号可以让python将pizza模块中的每个函数都复制到这个程序文件中。但一般不使用,因为若模块中有函数的名称与当前项目中使用的名称相同,可能会导致意外。

7 参考文献

python从入门到实践

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值